|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class MyIntsCollection { |
| 4 | + private MyInt[] myInts; |
| 5 | + |
| 6 | + // constructor |
| 7 | + public MyIntsCollection(MyInt[] integers) { |
| 8 | + this.myInts = integers; |
| 9 | + } |
| 10 | + |
| 11 | + // empty constructor |
| 12 | + public MyIntsCollection() { |
| 13 | + this.myInts = new MyInt[1]; |
| 14 | + } |
| 15 | + |
| 16 | + // This method sort the array of MyInts |
| 17 | + public MyInt[] sort(boolean isAsc) { |
| 18 | + MyInt[] sortedMyInts = Arrays.copyOf(this.myInts, this.myInts.length); |
| 19 | + int compareKey = isAsc ? +1 : -1; |
| 20 | + for (int i = 0; i < sortedMyInts.length - 1; i++) { |
| 21 | + for (int j = 1; j < sortedMyInts.length - i; j++) { |
| 22 | + if (sortedMyInts[j - 1].compareTo(sortedMyInts[j]) == compareKey) { |
| 23 | + // swap |
| 24 | + MyInt temp = sortedMyInts[j - 1]; |
| 25 | + sortedMyInts[j - 1] = sortedMyInts[j]; |
| 26 | + sortedMyInts[j] = temp; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return sortedMyInts; |
| 31 | + } |
| 32 | + |
| 33 | + // This method returns the index of MyInt in the array |
| 34 | + public int indexOf(MyInt other) { |
| 35 | + for (int i = 0; i < this.myInts.length; i++) { |
| 36 | + if (this.myInts[i].isEqual(other)) |
| 37 | + return i; |
| 38 | + } |
| 39 | + return -1; |
| 40 | + } |
| 41 | + |
| 42 | + // This method add element to the array |
| 43 | + public void append(MyInt other) { |
| 44 | + if (this.myInts[0] == null) { |
| 45 | + this.myInts[0] = other; |
| 46 | + } else { |
| 47 | + MyInt[] newArray = new MyInt[this.myInts.length + 1]; |
| 48 | + for (int i = 0; i < this.myInts.length; i++) |
| 49 | + newArray[i] = this.myInts[i]; |
| 50 | + newArray[this.myInts.length] = other; |
| 51 | + this.myInts = newArray; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // This method sum MyInts |
| 56 | + public MyInt sumAll() { |
| 57 | + MyInt sum = new MyInt("0"); |
| 58 | + for (int i = 0; i < this.myInts.length; i++) |
| 59 | + sum = sum.add(this.myInts[i]); |
| 60 | + return sum; |
| 61 | + } |
| 62 | + |
| 63 | + public String toString() { |
| 64 | + String str = ""; |
| 65 | + for (int i = 0; i < this.myInts.length; i++) |
| 66 | + str += this.myInts[i].toString() + "\n"; |
| 67 | + return str; |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + MyInt[] a = {new MyInt("23"), new MyInt("16"), new MyInt("51")}; |
| 72 | + MyIntsCollection collection = new MyIntsCollection(a); |
| 73 | + MyInt[] sortedArray = collection.sort(false); |
| 74 | + System.out.println(Arrays.toString(a)); |
| 75 | + System.out.println("sorted array: " + Arrays.toString(sortedArray)); |
| 76 | + System.out.println("index of 51: " + collection.indexOf(new MyInt("51"))); |
| 77 | + System.out.println("sum = " + collection.sumAll()); |
| 78 | + } |
| 79 | +} |
0 commit comments