Light Blue Pointer
본문 바로가기
개발일지

2023-11-23, Today I Learned

by 개발바닥곰발바닥!!! 2023. 11. 24.

⭐Java array deep copy 쉽게 할 수 없을까

1. clone

we’ll copy an array of primitive types using the clone method:
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();

2. stream

String[] strArray = {"orange", "red", "green'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);

 

 

⭐Java Set

import java.util.HashSet; 

HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.contains("Mazda");
cars.remove("Volvo");
cars.size();
cars.clear();

for (String i : cars) {
  System.out.println(i);
}
System.out.println(cars);

 

ArrayList to Array Conversion in Java : toArray() Methods

Note: toArray() method returns an array of type Object(Object[])

import java.io.*;
import java.util.List;
import java.util.ArrayList;
 
class GFG {
    public static void main(String[] args)
    {
        List<Integer> al = new ArrayList<Integer>();
        al.add(10);
        al.add(20);


        Object[] objects = al.toArray();//됨

        Integer[] objects = al.toArray();//안됨

        Integer[] arr = new Integer[al.size()];
        arr = al.toArray(arr);

		// ArrayList to Array Conversion
        for (int i = 0; i < al.size(); i++)
            arr[i] = al.get(i);
    }
}

 

 

⭐Java arrayList

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
	cars.get(0);
	cars.set(0, "Opel");
	cars.remove(0);
	cars.clear();
	cars.size();

	Collections.sort(cars);  // Sort cars

'개발일지' 카테고리의 다른 글

2023-11-29, Today I Learned  (0) 2023.11.29
2023-11-28, Today I Learned  (0) 2023.11.28
2023-11-22, Today I Learned  (0) 2023.11.22
2023-11-21, Today I Leanred  (0) 2023.11.21
2023-11-20, Today I Learned  (0) 2023.11.20