ALGORITHM/이론

ArrayList(선형리스트)

SZCODE 2020. 11. 9. 12:31
import java.util.ArrayList;
import java.util.Collections;


//1. ArrayList
public class test {
	//implements는 부모의 메소드를 반드시 오버라이딩(재정의)해야 한다.
	static class Person implements Comparable<Person>{
		int n;
		String name;
		
		Person(int n, String name){
			this.n = n;
			this.name = name;
		}
		
		  @Override
	      public int compareTo(Person o) {
	         
	           if(Integer.compare(this.n, o.n) == 1) {
	              return 1;
	           } else if(Integer.compare(this.n, o.n) == 0) {
	              return this.name.compareTo(o.name);
	           }
	           return -1;
	      }
	}
	
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList();
		list.add("A");
		list.add("Z");
		list.add("F");
		list.add("C");
		list.add("a");
		list.add("B");
		Collections.sort(list);
		System.out.println(list);//[A,B,C,F,Z,a]
		
//		list 요소 모두 지우기
//		list.clear();	
		
//		list 요소가 모두 비었으면 true, 아니면 false
		list.isEmpty();	
		
//		list에 A가 있으면 true, 없으면 false
		list.contains("A");
		
//		index 0번째 값 가져오기
		list.get(0);	
		
//		index 0번째 지우기
		list.remove(0);	
		
//		지정된 값 지우기
		list.remove("B");
		
//		list 크기
		list.size();	
		
//		String.valueOf(Object)를 통해서 toString()오버라이드 후 string으로 변환
		list.toString();
		
//		=======================================================
		ArrayList<Person> persons = new ArrayList();
		persons.add(new Person(1,"test1"));
		persons.add(new Person(5,"test5"));
		persons.add(new Person(8,"test8"));
		persons.add(new Person(4,"test4"));
		persons.add(new Person(3,"test3_2"));
		persons.add(new Person(3,"test3_1"));
		
		//Comparable을 상속 받아 정렬 
		//같은 n일 경우 name도 정렬됨
		Collections.sort(persons);
		
		//출력할 때 list.persons 하면 안됨
		for(Person p : persons) {
			System.out.println(p.n + " " + p.name);
		}
		
		
		
	
	}
}

'ALGORITHM > 이론' 카테고리의 다른 글

Bubble Sort. 버블정렬  (0) 2021.01.05
Insertion sort. 삽입정렬  (0) 2021.01.04
Selection sort. 선택정렬  (0) 2021.01.04
HashMap(해시테이블)  (0) 2020.11.14
[정올] 1169 주사위던지기1  (0) 2020.05.17