코테 준비

꿀이·2022년 1월 2일
0

정리

java로 코테를 한번 봐볼까...?


        //입력
        Scanner sc = new Scanner(System.in);
        String inputString = sc.next();
        int inputInteger = sc.nextInt();

        //문자열을 숫자로
        int num = Integer.parseInt(inputString);
        //숫자를 문자열로
        String str = Integer.toString(num);

        //2차원 배열 출력
        int arr[][] = new int[3][3];
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(" " + arr[i][j]);
            }
            System.out.println();
        }
                    
        //배열 정렬
        int arr[] = {1, 5, 2, 3, 4};
        Arrays.sort(arr);
        for (int i : arr) {
            System.out.print(i+ " ");
        }

	//ArrayList 정렬
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(5);
        arrayList.add(2);
        arrayList.add(3);
        Collections.sort(arrayList);

        System.out.println(arrayList);

내가 만든 객체 정렬하기

내가 만든 객체에 Comparable<> 인터페이스의 compareTo를 구현해서 Collections.sort(arrayList) 를 하면 정렬이 가능하다.

public static class Node implements Comparable<Node> {
        private int y;
        private int x;
        private int cost;

        @Override
        public int compareTo(Node node) {
            if (this.cost > node.cost) {
                return 1;//오름차순
            }else
                return -1;
        }
        
        
    public static void main(String[] args) {

        //ArrayList 정렬
        List<Node> arrayList = new ArrayList<>();
        arrayList.add(new Node(1, 1, 5));
        arrayList.add(new Node(1, 1, 2));
        arrayList.add(new Node(1, 1, 1));
        arrayList.add(new Node(1, 1, 4));
        arrayList.add(new Node(1, 1, 3));

        Collections.sort(arrayList);

        for (Node node : arrayList) {
            System.out.print(" " + node.getCost());
        }
    }
    
    //Arrays.sort() 에서도 가능하네!!
       Node arr[] = {new Node(1, 1, 5),
                new Node(1, 1, 4),
                new Node(1, 1, 1),
                new Node(1, 1, 2),
                new Node(1, 1, 3)};

        Arrays.sort(arr);

        for (Node node : arr) {
            System.out.print(" " + node.getCost());
        }

profile
내게 맞는 옷을 찾는중🔎

0개의 댓글