var은 값이 들어오면 타입결정
자바object랑 다트 dynamic이 비슷함
void main() { dynamic list = [1, 2, 3, 4]; list.add(5); dynamic newList = list; newList.add(6); print(newList); // 출력: [1, 2, 3, 4, 5, 6] print(list); // 출력: [1, 2, 3, 4, 5, 6] print(list.hashCode); print(newList.hashCode); }
컬렉션 복사
List<Integer> newList = new ArrayList<>(list);
package ex14.example1; import java.util.ArrayList; import java.util.List; public class CopyEx01 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); // 컬렉션 복사 List<Integer> newList = new ArrayList<>(list); System.out.println(list.hashCode()); System.out.println(newList.hashCode()); newList.add(5); System.out.println(list.hashCode()); System.out.println(newList.hashCode()); // 이전 // var newList = new ArrayList<>(); // for (int i = 0; i < list.size(); i++) { // newList.add(list.get(i)); // } } }
통째로 복사, 부분 복사
package ex14.example1; class User { private int id; private String name; private String tel; 2) public User(User user) { this.id = user.getId(); this.name = user.getName(); this.tel = user.getTel(); } public User(int id, String name, String tel) { this.id = id; this.name = name; this.tel = tel; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; } public int getId() { return id; } public String getName() { return name; } public String getTel() { return tel; } } public class CopyEx04 { public static void main(String[] args) { User u1 = new User(1, "ssar", "0102222"); // 1. 통째로 복사 1) User u2 = new User(u1.getId(), u1.getName(), u1.getTel()); 2) User u2 = new User(u1); // 2. 부분변경 복사 User u3 = new User(u1.getId(), u1.getName(), "0103333"); } }
Data Transfer Object
package ex14.example1; import java.time.LocalDateTime; // Data Transfer Object class JoinDTO { private String username; // ssar private String password; private String email; public JoinDTO(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public String getUsername() { return username; } public String getPassword() { return password; } public String getEmail() { return email; } } class Member { private int no; private String username; private String password; private String email; private LocalDateTime createdAt; public Member(int no, JoinDTO dto) { this.no = no; this.username = dto.getUsername(); this.password = dto.getPassword(); this.email = dto.getEmail(); this.createdAt = LocalDateTime.now(); } } public class CopyEx05 { public static void main(String[] args) { JoinDTO d1 = new JoinDTO("ssar", "1234", "ssar@nate.com"); JoinDTO d2 = new JoinDTO("cos", "1234", "cos@nate.com"); Member m1 = new Member(1, d1); Member m2 = new Member(2, d2); // 이전 // LocalDateTime now = LocalDateTime.now(); // System.out.println(now); } }
Share article