1 / 25

ArrayList Examples

ArrayList Examples. Constructor is of unsafe Type. You have to use –Xlint option to compile. Example 1. import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arr = new ArrayList(10); arr.add("A"); arr.add("B"); arr.add("C"); arr.add("X");

sukey
Download Presentation

ArrayList Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ArrayList Examples

  2. Constructor is of unsafe Type. You have to use –Xlint option to compile Example 1 import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arr = new ArrayList(10); arr.add("A"); arr.add("B"); arr.add("C"); arr.add("X"); arr.add("Y"); arr.add("Z"); } } E:\oop>javac arraylist.java Note: arraylist.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. E:\oop>javac -Xlint arraylist.java arraylist.java:6: warning: [unchecked] unchecked conversion found : java.util.ArrayList required: java.util.ArrayList<java.lang.String> ArrayList<String> arr = new ArrayList(10); ^ 1 warning

  3. Example 2 import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arr = new ArrayList<String>(10); arr.add("A"); arr.add("B"); arr.add("C"); arr.add("X"); arr.add("Y"); arr.add("Z"); } } Safe Constructor E:\oop>javac arraylist.java E:\oop>

  4. Example 3 Use of add for parametrized Type import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arr = new ArrayList(10); arr.add(new Integer(10));// Can not Hold Integer Objects arr.add("B"); arr.add("C"); arr.add("X"); arr.add("Y"); arr.add("Z"); } } E:\oop>javac arraylist.java arraylist.java:7: cannot find symbol symbol : method add(java.lang.Integer) location: class java.util.ArrayList<java.lang.String> arr.add(new Integer(10)); ^ Note: arraylist.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 error

  5. Example 3 cont.. Use of add for parametrized Type import java.util.*; class arraylist { public static void main(String args[]) { ArrayList<String> arr = new ArrayList<String>(10); arr.add(10); arr.add("C"); arr.add("X"); arr.add("Y"); arr.add("Z"); } } E:\oop>javac arraylist.java arraylist.java:7: cannot find symbol symbol : method add(int) location: class java.util.ArrayList<java.lang.String> arr.add(10); ^ 1 error

  6. Adding/Removing Elements In/From an ArrayList • Use add method For Adding Elements • void add(Object obj); // Adds in the last • void add(int index,Object Obj) // Adds at index i • Examples : ArrayList ar = new ArrayList(); ar.add(new Integer(10)); ar.add(“X”); ar.add(1,”Y”); • Use remove() method for removing Eleements • void remove(Object obj) // removes obj from list if exists • void remove(int index) // removes element from index i. But I should be within permitted range

  7. For changing the Elements • Use set method for changing the values for individual eleemnts • void set(int index, Object Value) • index should be within permitted range • Sets element at index by Value

  8. import java.util.*; class arrex1 { public static void main(String args[]) { ArrayList arr = new ArrayList(); // Adding Elements arr.add("A"); arr.add("B"); arr.add(new Integer(10)); arr.add(2,new Integer(10)); arr.add(new Float(10.56f)); arr.add(new Boolean(true)); arr.add(new Double(10.56)); System.out.println(arr); [A, B, 10, 10, 10.56, true, 10.56]

  9. // Removing Elements arr.remove("B"); System.out.println(arr); arr.remove(2); System.out.println(arr); arr.set(2,"Object"); arr.set(4,"Java"); System.out.println(arr); } } Removes “B” From List [A, 10, 10, 10.56, true, 10.56] Removes element from index 2 from List [A, 10, 10.56, true, 10.56] Sets value for index 2 element as “Object” Sets value for index 4 element as “Java” [A, 10, Object, true, Java]

  10. sum.java:22: operator + cannot be applied to int,java.lang.Object sum = sum + integers.get(i); // Sum of integers Stored in an Unparametrized Arrayslists import java.util.*; class sum { public static void main(String args[]) { ArrayList integers = new ArrayList(10); // Adding Elements integers.add(10); integers.add(-5); integers.add(12); integers.add(-34); integers.add(3,90); integers.add(3,-110); int sum=0; // Forward Traversing Using for loop for(int i=0;i< integers.size();i++) sum = sum + integers.get(i); System.out.println("Sum ="+sum); } } What’s Wrong Here ArrayList in use is Unparametrized. While getting/retrieving elements, We have to typecast it to base type beforeuse

  11. Write For Loop as follows int sum=0; // Forward Traversing Using for loop for(int i=0;i< integers.size();i++) sum = sum + ((Integer)integers.get(i)).intValue(); System.out.println("Sum ="+sum); Type Cast to base type and then use

  12. Backward Traversal Using for loop int sum=0; // Forward Traversing Using for loop for(int i = integers.size()-1; i>=0; i++) sum = sum + ((Integer)integers.get(i)).intValue(); System.out.println("Sum ="+sum);

  13. Use of iterators ONLY FORWARD TRAVERSAL int sum=0; // STEP1 get an iterator for ArrayList Iterator itr = integers . iterator(); while(itr.hasNext()) sum = sum + ((Integer)itr.next()).intValue(); System.out.println("Sum ="+sum);

  14. Use of ListIterator // Forward Traversal // Get ListIterator and set at the beginning of Array List ListIterator Litr = integers.listIterator(); // Use while loop with hasNext while(Litr.hasNext() { sum = sum + ((Integer)itr.next()).intValue(); } System.out.println("Sum ="+sum); // Backward Traversal // Get ListIterator and set at the End of Array List ListIterator Litr = integers.listIterator(integers.size()); // Use while loop with hasPrevious while(Litr.hasPrevious() { sum = sum + ((Integer)itr.previous()).intValue(); } System.out.println("Sum ="+sum);

  15. What’s Wrong in the Following code ArrayList<Integer> x = new ArrayList<Integer>(10); // Adding Elements x.add(10); x.add(-5); x.add(12); x.add(-34); x.add(3,90); x.add(3,-110); int sum=0; for(int i=0;i<x.size();i++) sum = sum+x.get(i).intValue(); NOTHING

  16. Unparametrized Type Iterator What’s Wrong in the Following code ArrayList<Integer> x = new ArrayList<Integer>(10); // Adding Elements x.add(10); x.add(-5); x.add(12); x.add(-34); x.add(3,90); x.add(3,-110); int sum=0; Iterator itr = x.iterator(); while(itr.hasNext()) sum = sum+x.next().intValue(); E:\oop>javac sum.java sum.java:19: cannot find symbol symbol : method intValue() location: class java.lang.Object sum = sum+itr.next().intValue(); ^ sum.java:19: operator + cannot be applied to int,java.lang.Object.intValue sum = sum+itr.next().intValue(); ^ sum.java:19: incompatible types found : <nulltype> required: int sum = sum+itr.next().intValue(); ^ 3 errors next() returns an Object Type for unparametrized Iterator

  17. What’s Wrong in the Following code ArrayList<Integer> x = new ArrayList<Integer>(10); // Adding Elements x.add(10); x.add(-5); x.add(12); x.add(-34); x.add(3,90); x.add(3,-110); int sum=0; Iterator<Integer> itr = x.iterator(); while(itr.hasNext()) sum = sum+x.next().intValue(); Parametrized Iterator NOTHING

  18. Implement Following Methods • void sort(ArrayList<String> names, boolean isAscending) • Sorts the String elements of the names either in acscending or descending order. Do the change in original names list. It is not like you store the sorted elements in another list and returns. 2. double sum(ArrayList<Integer> integers) [Text Book Example] 3. static ArrayList<String> union(ArrayList<String> s1, ArrayList<String> s2) 4. static ArrayList<String> intersection (ArrayList<String> s1, ArrayList<String> s2) 5. public static BOX getHighestVolumeBox(ArrayList<BOX> boxes) 6. public static BOX getLowestVolumeBox(ArrayList<BOX> boxes) • public static ArrayList<BOX> getBoxesWithArea(ArrayList<Box> boxlist, double area) • public static boolean hasDuplicates(ArrayList ar) // returns true if arrayList has any duplicate elements otherwise false

  19. Sort() Method static void sort(ArrayList<String> names,boolean isAscending) { if(isAscending){ for(int i=0;i<names.size();i++) { for(int j=i+1;j<names.size();j++) { String str1 = names.get(i); String str2 = names.get(j); if(str1.compareTo(str2) > 0) { String temp = names.get(i); names.set(i,str2); names.set(j,str1); } } } } if(!isAscending){ for(int i=0;i<names.size();i++) { for(int j=i+1;j<names.size();j++) { String str1 = names.get(i); String str2 = names.get(j); if(str1.compareTo(str2) < 0) { String temp = names.get(i); names.set(i,str2); names.set(j,str1); } } } } } } // End of sort method

  20. ADD ELEMENTS FROM FIRST LIST AS ITIS Search elements of f2 in f1. Add which one does not exists Union() method static ArrayList<String> union(ArrayList<String> f1,ArrayList<String> f2) { ArrayList<String> f3 = new ArrayList<String>(); for(int i=0;i<f1.size();i++) f3.add(f1.get(i)); for(int i=0;i<f2.size();i++) { String temp = f2.get(i); if(f1.contains(temp)) continue; else f3.add(temp); } return f3; } // End of union

  21. import java.util.*; class BOX { private double length,width,height; BOX(double l,double b,double h) { length = l; width = b; height = h; } BOX(BOX other) { // this = other ; WRONG this variable is final this.length = other.length; this.width = other.width; this.height = other.height; } public double area() { return 2*(length*width+width*height+height*length); } public double volume() { return length*width*height; } Complete BOX ArrayList Example

  22. public boolean isEqual(BOX other) { if (area() == other.area()) return true; return false; } public static boolean isEqual(BOX first,BOX second) { if (first.area() == second.area()) return true; return false; } public int compareTo(BOX other) { if(area() > other.area()) return 1; if(area() < other.area()) return -1; return 0; } public static int compareTo(BOX first,BOX second) { if(first.area() > second.area()) return 1; if(first.area() < second.area()) return -1; return 0; }

  23. public String toString() { String s1 = "length:"+length; String s2 = "Width:"+width; String s3 = "Height:"+height; return s1+s2+s3+"Area:"+area()+"Volume:"+volume(); } } // End of BOX class

  24. class boxarraylist { public static BOX getHighestVolumeBOX(ArrayList<BOX> boxes) { BOX highestBOX = boxes.get(0); for(int i=1;i<boxes.size();i++) if(highestBOX.volume() < boxes.get(i).volume()) highestBOX = boxes.get(i); return highestBOX; } public static BOX getLowestVolumeBOX(ArrayList<BOX> boxes) { BOX lowestBOX = boxes.get(0); for(int i=1;i<boxes.size();i++) if(lowestBOX.volume() > boxes.get(i).volume()) lowestBOX = boxes.get(i); return lowestBOX; } /* Complete The following methods static void sortByVolume(ArrayList<BOX> boxes, boolean isAscending); static void sortByArea(ArrayList<BOX> boxes, boolean isAscending); */ }

  25. class test { public static void main(String args[]) { ArrayList<BOX> boxes = new ArrayList<BOX>(); boxes.add(new BOX(10,6,8)); boxes.add(new BOX(12,16,18)); boxes.add(new BOX(6,6,8)); boxes.add(new BOX(20,16,18)); boxes.add(new BOX(1,6,8)); BOX b1 = boxarraylist.getHighestVolumeBOX(boxes); BOX b2 = boxarraylist.getLowestVolumeBOX(boxes); System.out.println(b1); System.out.println(b2); } } E:\oop>javac arraylist2.java E:\oop>java test length:20.0Width:16.0Height:18.0Area:1936.0Volume:5760.0 length:1.0Width:6.0Height:8.0Area:124.0Volume:48.0

More Related