'ArrayList'에 개체를 추가하려고 하는데 'objt(이름, 주소, 연락처)'의 3가지 특성을 가진 'ArrayList'에 개체를 추가할 때마다 오류가 발생합니다.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
ArrayList<Data> Contacts = new ArrayList<Data>();
Data objt = new Data();
Contacts.add(objt.Data(name, address, contact));
}
}
여기서 '데이터'는 I'm이 객체를 만들어 '어레이리스트'에 전달하려고 하는 클래스이다.
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public void Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public void printData(){
System.out.println("Name\tAddress\tContactNo");
System.out.println(name + "\t" + address + "\t" + cell);
}
}
개체를 생성할 때 'new' 연산자를 사용해야 합니다.
Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step
그렇지 않으면
Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list
그리고 생성자에는 'doct'가 포함되어야 합니다. 그렇지 않으면 그것은 당신의 수업에서 하나의 방법이 됩니다.
public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such
다음 중 하나를 사용해 보십시오.
Data objt = new Data(name, address, contact);
Contacts.add(objt);
인스턴스화하려면 여기서 새 연산자를 사용해야 합니다. 예:
Contacts.add(new Data(name, address, contact));