Examples of smaller Java programs that do various interesting things.

CreateASet.java 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import java.util.Arrays;
  2. import java.awt.Rectangle;
  3. /**
  4. * A sample of a ploymorphic method.
  5. * @author scottm
  6. *
  7. */
  8. public class CreateASet {
  9. public static void main(String[] args){
  10. String[] words = {"A", "B", "B", "D", "C", "A"};
  11. System.out.println( "original: " + Arrays.toString(words));
  12. System.out.println( "as a set: " + Arrays.toString(makeSet(words)));
  13. Rectangle[] rectList = {new Rectangle(), new Rectangle(),
  14. new Rectangle(0, 1, 2, 3), new Rectangle(0, 1, 2, 3)};
  15. System.out.println( "original: " + Arrays.toString(rectList));
  16. System.out.println( "as a set: " + Arrays.toString(makeSet(rectList)));
  17. Object[] mixed = {"A", "C", "A", "B", new Rectangle(),
  18. new Rectangle(), "A", new Rectangle(0, 1, 2, 3), "D"};
  19. System.out.println( "original: " + Arrays.toString(mixed));
  20. System.out.println( "as a set: " + Arrays.toString(makeSet(mixed)));
  21. }
  22. /**
  23. * An example of polymorphism in action. The method relies
  24. * on Java's inheritance requirement and polymorhphism to call
  25. * the correct equals method.
  26. * @param data != null, no elements of data are null
  27. * @return a Set (no duplicates) of the elements in data.
  28. */
  29. public static Object[] makeSet(Object[] data){
  30. assert data != null : "Failed precondition makeSet. parameter cannot be null";
  31. assert noNulls(data) : "Failed precondition makeSet. no elements of parameter can be null";
  32. Object[] result = new Object[data.length];
  33. int numUnique = 0;
  34. boolean found;
  35. int indexInResult;
  36. for(int i = 0; i < data.length; i++){
  37. // maybe should break this out into another method
  38. indexInResult = 0;
  39. found = false;
  40. while(!found && indexInResult < numUnique){
  41. found = data[i].equals(result[indexInResult]);
  42. indexInResult++;
  43. }
  44. if( ! found ){
  45. result[numUnique] = data[i];
  46. numUnique++;
  47. }
  48. }
  49. Object[] result2 = new Object[numUnique];
  50. System.arraycopy(result, 0, result2, 0, numUnique);
  51. return result2;
  52. }
  53. // pre: data != null
  54. // return true if all elements of data are non null,
  55. // false otherwise
  56. private static boolean noNulls(Object[] data){
  57. assert data != null : "Failed precondition makeSet. parameter cannot be null";
  58. boolean good = true;
  59. int i = 0;
  60. while( good && i < data.length ){
  61. good = data[i] != null;
  62. i++;
  63. }
  64. return good;
  65. }
  66. }