http://cafe.daum.net/ComputerScience1 다음 ConputerScience 카페에서 퍼온 내용.
이번에 작업하면서 많은 도움을 받았다. 굿!!

java.util.* 콜렉션 사용하기

ArrayTest:

                      

             int [] values = new int[3];

              

             // init

             Arrays.fill(values, 0);

              

             values[0] = 2; values[1] = 1; values[2] = 3;

              

             // .length 이용하여 for문을 사용하는 방법 대신, collection 이용

             for(int oneElem : values){

                    System.out.println(oneElem);

             }     

              

             // compare

             int [] values2 = { 1, 1, 3 };

             if(java.util.Arrays.equals(values, values2)) {

                    System.out.println("equal");

             } else {

                    System.out.println("not equal");

             }

              

             // sort

             Arrays.sort(values);

              

             // search

             int [] values3 = { 10, 5, 6, 8, 7, 2, 1};

             java.util.Arrays.sort(values3);

             int position = java.util.Arrays.binarySearch(values3, 7);

             System.out.println("found value: "+values3[position]);

              

              

Vector:

ArrayList Vector 유사하지만 ArrayList 다중 쓰레드에서 안저하지 않음

             String [] str = {"test1", "test2"};

              

             // create

Vector<String> vValue = new Vector<String>( java.util.Arrays.asList(str));

              

             // add a value

             vValue.add("test5");      

              

             // add array

             // List<String> nameList = java.util.Arrays.asList(addStr);

             String [] addStr = {"test4", "test3"};

             vValue.addAll(Arrays.asList(addStr));

             System.out.println(vValue.lastElement());    

              

             // traverse by collection

             for(String oneElem:vValue){

                    System.out.println(oneElem);

             }

              

             // traverse by Iterator

             System.out.println("Vector Elements");

             Iterator<String> iter = vValue.iterator();

              while(iter.hasNext()) {

                    System.out.println(iter.next());

             }

              

             // get subList

             List<String> subList = vValue.subList(2,3);

              

              

             // sort: asc

             System.out.println("Vector Sort Asc");

             Collections.sort(vValue);

             for(String oneElem:vValue){

                    System.out.println(oneElem);

             }

              

             // sort: desc

             System.out.println("Vector Sort Desc");

             Comparator<String> r = Collections.reverseOrder();

             Collections.sort(vValue, r);

             for(String oneElem:vValue){

                    System.out.println(oneElem);

             }

              

             // remove

             vValue.remove(1);                // remove second element

             vValue.removeAllElements();      // remove all element

              

             System.out.println("IsEmpty: "+vValue.isEmpty());

              

             System.out.println("Vector<UserClas> Test:");

             Vector<Person> personVector = new Vector<Person>();

             personVector.add(new Person("f1","kim"));

             personVector.add(new Person("f2","park"));

             personVector.add(new Person("f3","lee"));

              

             Collections.sort(personVector);

             for(Person oneElem:personVector){

                    System.out.println(oneElem);

             }

              

        

Stack:

             Stack<String> sValue = new Stack<String>();

              

             sValue.push("stack1");

             sValue.push("stack2");

             sValue.push("stack3");

              

             // shuffle for fun

             Collections.shuffle(sValue);

              

              while(!sValue.empty()){

                    System.out.println(sValue.pop());

             }

              

        

HashMap:

             // HashMap<Key, Value>

             HashMap<String,Integer> aMap = new HashMap<String,Integer>();

        

             // if a key already exists, replace current value with new value

             // key: String's hashCode() method

             aMap.put("1st", new Integer(100));

             aMap.put("2nd", new Integer(200));

             aMap.put("3nd", new Integer(300));

             aMap.put("4nd", new Integer(400));

              

             // get

             Integer firstValue = aMap.get("1st");

             System.out.println("firstValue: "+firstValue);

              

             // remove

             Integer removeVal!ue = aMap.remove("4nd");

             System.out.println("removeVal!ue: "+removeVal!ue);

              

             // replace

             Integer oldValue = aMap.put("2nd", new Integer(210));

             System.out.println("oldValue: "+oldValue + ", newValue:" +

                                                     aMap.get("2nd"));

              

             // traverse key

             System.out.println("Key: ");

             Set<String> keys = aMap.keySet();

             for(String key : keys) {

                    System.out.println(key);

             }

              

             // traverse value

             System.out.println("Values: ");

             Collection<Integer> collection = aMap.values();

             for(Integer i : collection) {

                    System.out.println(i);

             }

              

             // traverse entry(key,value pair)

             System.out.println("Values: ");

             Set<Map.Entry<String, Integer>> entries = aMap.entrySet();

             for(Map.Entry<String, Integer> i : entries) {

                    System.out.println("Key:" + i.getKey() +", Value:" + i.getValue());

             }

              

             // get Sorted Values

             System.out.println("Sorted Values: ");

             LinkedList<Integer> values = new LinkedList<Integer>(aMap.values());

             Collections.sort(values); // Sort the entries

             for(Integer entry : values) {

                    System.out.println(entry);

             }

        

PriorityQueue:

              

             // asc ordered queue

             Queue<String> queue = new PriorityQueue<String>();

               

             queue.add("item5");

             queue.add("item7");

             queue.add("item3");

             queue.add("item1");

              

             // traverse

             for(String queueItem:queue){

                    System.out.println(queueItem);

             }

             // extract elements by priority

             while(!queue.isEmpty()){

                    System.out.println(queue.remove());

             }

        

Comparable 클래스:

Vector<T> 콜렉션에서 타입 T로 사용자 정의 클래스를 사용하면서 콜렉션의 정렬 메소드를 사용하려면 Comparable<T>를 구현하여야 함.

public class Person implements Comparable<Person>{

       private String firstName;

       private String lastName;

        

       // Constructor

       public Person(String firstName, String lastName) {

             this.firstName = firstName;

             this.lastName = lastName;

       }

        

       public String toString() {

             return firstName + ": " + lastName;

       }

       // Compare Person objects

       public int compareTo(Person person) {

             // -: this.lastName, person.lastName, 0: same, +:person.lastName,

// this.lastName

             int result = lastName.compareTo(person.lastName);

              

             if( result == 0){

                    // if it has same last name, compare first name

                    return firstName.compareTo(((Person)person).firstName);

             }

             // otherwise

             return result;

              

       }

}

Collection Algorithm:

콜렉션 알고리즘은 Collections.메소드(…) 형태로 사용하면 

sort()

shuffle()

reverse()

fill()

copy()

swap()

addAll()

binarySearch()

frequency()

disjoint()

min()

max()


+ Recent posts