Character/String/Array/List

Character

// 선언
Character c1 = 's';
Character c2 = 'k';

// 비교 
boolean b = c1 == c2;

// char to String
String str = char1 + "";

// char 문자인지 숫자인지 확인
System.out.println(Character.isLetter(c1));
System.out.println(Character.isDigit(c1));

String

public class Main
{
    public static void main(String[] args)
    {
        String str = "SoooBin";
        String str2 = "SoooBin";
        String str3 = new String("SoooBin");
        String str4 = "SoooBin22";
        String str5 = "  SooBin Jung  ";
        System.out.println(str.length()); // 7
        System.out.println(str == str2); // true
        System.out.println(str == str3); // false
        System.out.println(str.equals(str2)); // true
        System.out.println(str.equals(str3)); // true
        System.out.println(str.compareTo(str2)); // 0
        System.out.println(str.compareTo(str4)); // -2
        System.out.println(str.contains("oo")); // true
        System.out.println(str5.trim()); // "SooBin Jung"

    }
}

replace

public class Main
{
    public static void main(String[] args)
    {
        String str = "Hello, World_123!!";
        String charsToRemove = ",_!";
 
        for (char c : charsToRemove.toCharArray()) {
            str = str.replace(String.valueOf(c), "");
        }
 
        System.out.println(str);
    }
}
// Hello World123

replaceAll

public class Main
{
    public static void main(String[] args)
    {
        String str = "Hello, World_123!!";

        str = str.replaceAll("[^\\w+]", "");
        System.out.println(str);
    }
}
// HelloWorld_123

indexOf(), lastIndexOf()

public class Main
{
    public static void main(String[] args)
    {
        String str = "Sooobin";

        int a = str.indexOf("o"); // 1
        int b = str.indexOf("o", 2); // 2
        int c = str.lastIndexOf("o"); // -1 (no o from index 3

        System.out.println(a + " : " +  str.charAt(a)); // 1o (index 1 is o
        System.out.println(b + " : " + str.charAt(b)); // 2o (index 2 is o
        System.out.println(c + " : " + str.charAt(c)); // 3o (index 3 is o
    }
}
// 1 : o
// 2 : o
// 3 : o

toUpperCase(), toLowerCase()

public class Main
{
    public static void main(String[] args)
    {
        String str = "SoooBin";

        System.out.println(str.toUpperCase());
        System.out.println(str.toLowerCase());
    }
}
// SOOOBIN 
// sooobin

startsWith("str2"), endWith("str2")

public class Main
{
    public static void main(String[] args)
    {
        String str = "SoooBin";
        System.out.println(str.startsWith("S")); // true
        System.out.println(str.startsWith("s")); // false
        System.out.println(str.endsWith("Bin")); // true
        System.out.println(str.endsWith("bin")); // false

    }
}

substring(incl,excl)

str.substring(incl,excl)
// incl: inclusive index, included, 
// excl: exclusive index, exclude

public class Main
{
    public static void main(String[] args)
    {
        String str = "SooBin Jung";
        // substring() 메소드를 사용하여 문자열을 추출
        String str1 = str.substring(0, 6);
        String str2 = str.substring(6);

        System.out.println(str1); // SooBin
        System.out.println(str2); //  Jung
    }
}

split("regrex")

str_array = str.split(“ “);
//return string array separated by spaces. 
// “Hello world” returns [“Hello”,”world”]
public class Main
{
    public static void main(String[] args)
    {
        String str = "SooBin Jung";
        // split
        String[] strArr = str.split(" ");
        for (String s : strArr)
        {
            System.out.println(s);
        }
    }
}

Array

// 선언
int[] arr;
int arr[];
int[] arr = new int[5]; //5의 크기를 가지고 초기값 0으로 채워진 배열 생성
String[] arr = new String[5]; 

int[] arr = {1,2,3,4,5}; 
int[] arr = new int[]  {1,3,5,2,4};    
int[] odds = {1,3,5,7,9};  
String[] weeks = {"월","화","수","목","금","토","일"};

// 배열 크기
int len = arr.length; 

// 2차원 배열 선언
int[][] arr = new int[4][3];   //3의 크기의 배열을 4개 가질 수 있는 2차원 배열 할당  
int[][] arr9 = { {2, 5, 3}, {4, 4, 1}, {1, 7, 3}, {3, 4, 5}};

// 객체(Class) 배열 선언
Student[] StudentArr = new Student[5];     //Student Class의 인스턴스 최대 5개 할당할 수 있는 배열
//StudentArr[0] >> null ...

Ref : https://ifuwanna.tistory.com/231

Sort

// Arrays.sort()
Arrays.sort(arr);
Arrays.sort(arr, Collections.reverseOrder());
Arrays.sort(arr, Comparator.reverseOrder());
// Array to List
Arrays.asList(arr);

copy, fill

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        int[] a = new int[10];
        Arrays.fill(a, 5);
        for (int j : a) {
            System.out.println(j);
        }

        System.out.println("----");

        int[] d = new int[10];
        Arrays.fill(d, 2, 5, 10);
        for (int j : d) {
            System.out.println(j);
        }
        
        System.out.println("----");

        int[] b = Arrays.copyOf(a, 2);
        for (int j : b) {
            System.out.println(j);
        }

        System.out.println("----");

        int c[] = Arrays.copyOfRange(a, 2, 7);
        for (int j : c) {
            System.out.println(j);
        }
    }
}

Print

// 그냥 매열을 출력할 경우 메모리의 주소값이 출력된다.  
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr);
// [I@762efe5d

// 반복문 사용하여 출력
int[] arr = {1, 2, 3, 4, 5};

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

// 1
// 2
// 3
// 4
// 5

// Arrays의 toString 사용하여 출력
import java.util.Arrays;

int[] arr = {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(arr));

// [1, 2, 3, 4, 5]

List

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main
{
    public static void main(String[] args)
    {
        // LinkedList Example
        List<String> arr = new ArrayList<>();
        // example of using methods in ArrayList
        arr.add("D");
        arr.add("E");
        arr.add("F");
        arr.add("G");
        arr.add("H");
        arr.add("I");
        arr.add("J");
        arr.add("A");
        arr.add("B");
        arr.add("C");


        System.out.println("ArrayList: " + arr);
        System.out.println("Size of ArrayList: " + arr.size());
        System.out.println("Element at index 5: " + arr.get(5));
        System.out.println("Index of element 'D': " + arr.indexOf("D"));
        System.out.println("Is ArrayList empty? " + arr.isEmpty());
        System.out.println("Does ArrayList contain 'E'? " + arr.contains("E"));
        System.out.println("Remove element 'E': " + arr.remove("E"));
        System.out.println("ArrayList after removing 'E': " + arr);
        System.out.println("Size of ArrayList after removing 'E': " + arr.size());
        System.out.println("Is ArrayList empty? " + arr.isEmpty());
        System.out.println("Does ArrayList contain 'E'? " + arr.contains("E"));
        System.out.println("Clear ArrayList");

        System.out.println("ArrayList before sorting: " + arr);
        Collections.sort(arr); //sorts arraylist
        System.out.println("ArrayList after sorting: " + arr);
    }
}
List<String> arr = new ArrayList<>();

arr.add(e);
arr.add(i,e);
arr.contains(e); //returns bool
arr.get(e);
arr.get(i);
arr.size();
arr.remove(e); //returns bool
arr.remove(i);//returns bool
arr.toArray();
arr.indexOf(e);
arr.set(i,e);
Collections.sort(arr); //sorts arraylist

오름차순 / 내림차순

배열

## 오름차순
import java.util.Arrays;

public class Sort {
	public static void main(String[] args)  {	
		int[] array = {58, 32, 64, 12, 15, 99};
		
		Arrays.sort(array);
		
		for(int i = 0; i < array.length; i++)
		{
			System.out.print("[" + array[i] + "] ");
		}
	}
}

## 내림차순
import java.util.Arrays;
import java.util.Collections;

public class Sort {
	public static void main(String[] args)  {	
		Integer[] array = {58, 32, 64, 12, 15, 99};
		
		Arrays.sort(array, Collections.reverseOrder());
		
		for(int i = 0; i < array.length; i++)
		{
			System.out.print("[" + array[i] + "] ");
		}
	}
}

출처: [https://crazykim2.tistory.com/462](https://crazykim2.tistory.com/462) [차근차근 개발일기+일상:티스토리]

컬렉션

import java.util.Arrays;
import java.util.Collections;

public class Sort {
	public static void main(String[] args) {    
		String[] str = {"a", "1", "가", "A", "3", "나"};
		List<String> list = Arrays.asList(str);	// 테스트를 위해..        

		System.out.println(list.toString());	// 정렬 전 출력
		
		Collections.sort(list);
		System.out.println(list.toString());	// 오름차순 정렬 후 출력
        
		Collections.reverse(list);        
		System.out.println(list.toString());	// 내림차순 정렬 후 출력
	}
}

출처: [https://haenny.tistory.com/349](https://haenny.tistory.com/349) [Haenny:티스토리]

기타

## Stream
List<Integer> nums = -something-;
nums = nums.stream()
    .map(n -> n * 2)
    .filter(n -> n >= 0)
    .collect(Collectors.toList());
    

## ASCII code
- A ~ Z : 65 ~ 90
- a ~ z : 97 ~122

## Math
Math.max(n1, n2);
Math.min(n1, n2);
Math.abs(n);
Math.pow(base, exponent);
Math.sqrt(n);
Math.round(n);
Math.floor(n);
Math.ceil(n);

## Comparator
public class MySort implements Comparator<int[]>{
       public int compare(int[] a, int[] b){
             return a[0]-b[0];
       }
 }

## Iterator
Iterator itr = array_name.iterator(); //or list.iterator()

itr.hasNext(); //returns bool
itr.next();
itr.remove(); //removes curr element

## %10 /10

## Random
Random r = new Random();
r.nextInt(n); //return a random int from 0 to n

// OR

Math.random(); //returns a random double between 0.0 and 1.0

## Java 정수의 최대/최소값
static int Integer.MAX_VALUE
static int Integer.MIN_VALUE

Last updated