mojo's Blog

vector와 HashMap, Collections 클래스의 활용 본문

Java

vector와 HashMap, Collections 클래스의 활용

_mojo_ 2021. 7. 20. 01:17
import java.util.*;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner=new Scanner(System.in);
		
		Vector<Integer> v=new Vector<Integer>();
		v.add(5);
		v.add(4);
		v.add(-1);
		v.add(2,100);
		
		System.out.println("size : "+v.size()+" capacity : "+v.capacity());
		
		for(int i=0;i<v.size();i++) {
			System.out.println(v.get(i));
		}
		
		HashMap<String, Integer> scoreMap = new HashMap<String, Integer>();
		
		scoreMap.put("김성동", 97);
		scoreMap.put("조성동", 88);
		scoreMap.put("박현동", 99);
		scoreMap.put("조길준", 70);
		scoreMap.put("형길집", 57);
		
		Set<String> keys=scoreMap.keySet();
		Iterator<String> it=keys.iterator();
		while(it.hasNext()) {
			String name=it.next();
			int score=scoreMap.get(name);
			System.out.println(name+" : "+score);
		}
		
		scanner.close();
	}

}


Collections 클래스를 활용하여 벡터, HashMap 등의 Key 값들을 Sorting 하거나 Max, Min 찾기, Binary search 가 가능하다.

import java.util.*;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner=new Scanner(System.in);
		
		Vector<Integer> v=new Vector<Integer>();
		v.add(5);
		v.add(4);
		v.add(-1);
		v.add(2,100);
		
		Collections.sort(v);
		
		for(int i=0;i<v.size();i++) {
			System.out.println(v.get(i));
		}
		
		int index=Collections.binarySearch(v, 4);
		System.out.println(4+"'s index : "+(index+1));
		
		int maxNum=Collections.max(v);
		int minNum=Collections.min(v);
		System.out.println("Max : "+maxNum+", Min : "+minNum);
		
		scanner.close();
	}

}

'Java' 카테고리의 다른 글

명품 JAVA Programming 제 7장 Open Challenge  (0) 2021.07.22
Generic class, method  (0) 2021.07.20
명품 JAVA Programming 제 6장 Open Challenge  (0) 2021.07.20
Math 클래스 메소드 활용  (0) 2021.07.20
StringBuffer 클래스  (0) 2021.07.20
Comments