Monday, February 7, 2011

Arraylist and Set Example

package mypackage;


import java.util.*;

public class FirstIterator {

      public static void main(String[] args) {
            ArrayList a = new ArrayList();
            //Set b = new HashSet();
            //String[] values = {"java","java2"};
            String abc = "hi";
            String abc1="hello";
           
            a.add(abc);
            a.add(abc1);
           
            //System.out.println(a.size());
            int i =0;
      try
            for(Iterator a1 = a.iterator();a1.hasNext();)
            {
                  String myword=(String)a.get(i);
                  System.out.println(myword);
                  i++;
            }
      }
      catch (Exception e)
      {
            System.out.println("Done");
      }
      }

}


To use set

import java.util.HashSet;
import java.util.Set;

public class FindDups {
public static void main(String args[]) {
Set s = new HashSet();
String[] values = new String[] { "java", "java2", "java2s", "javas",
"java" };
for (int i = 0; i < values.length; i++)
if (!s.add(values[i]))
System.out.println("Duplicate detected: " + values[i]);

System.out.println(s.size() + " distinct words detected: " + s);
}
}

No comments:

Post a Comment