티스토리 뷰

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

class Patient{
	String name;
	public Patient(String name) {
		this.name=name;
	}
}

public class ArrayList55 {
	public static void main(String[] args) {
		List ps=new ArrayList();
		Patient p2=new Patient("Mike");
		ps.add(p2);
        
		// insert code here
        
		System.out.println("f="+f);
		if(f>=0) {
			System.out.print("Mike Found");
		}
	}
}

Which code fragment, when inserted at line 14, enables 14, enables the code to print Mike Found?

A. int f = ps.indexOf(p2);

B. int f = ps.indexOf(Patient ("Mike"));

C. int f = ps.indexOf(new Patient "Mike"));

D. Patient p = new Patient("Mike");

int f = ps.indexOf(p);

 

정답: A

결과: 

Mike Found

해설:

List 클래스의 indexOf에 대한 이해를 묻는 문제이다.

java.util.List.indexOf(Object o) 에 관해 살펴보면

int java.util.List.indexOf(Object o)

  • indexOfint indexOf(Object o)

    Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

    Parameters:o - element to search forReturns:the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the elementThrows:ClassCastException - if the type of the specified element is incompatible with this list (optional)NullPointerException - if the specified element is null and this list does not permit null elements (optional)

 

스트링 클래스의 indexOf 메소드 처럼 리스트에 엘리먼트가 있으면 첫번째 인덱스를 리턴한다. 없으면 -1을 리턴한다.

 

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

class Patient{
	String name;
	public Patient(String name) {
		this.name=name;
	}
}

public class ArrayList55 {
	public static void main(String[] args) {
		List ps=new ArrayList();
		Patient p2=new Patient("dd");
		ArrayList55 a2=new ArrayList55();
		ps.add(a2);
		ps.add(p2);
		int f = ps.indexOf(p2);
		System.out.println("f="+f);
		if(f>=0) {
			System.out.print("Mike Found");
		}
	}
}

결과:

f=1
Mike Found

해설:

리스트에 a2,p2 엘리먼트가 있고 Patient 엘리먼트가 2번째에 있으니 indexOf에 의해 1를 리턴한다. 그래서 f는 1이고 0보다 크니 Mike Found를 출력한다.

보기 B는 

int f =ps.indexOf(Patient ("Mike")); -> int f =ps.indexOf(new Patient ("Mike"));

처럼 new를 써줘야 되고

보기 C는

int f =ps.indexOf(Patient "Mike"); -> int f =ps.indexOf(new Patient ("Mike"));

Mike에 괄호를 해야하고

보기 D는

객체 생성은 제대로 했는데 리스트에 add를 하지 않아서 엘리먼트가 없으니 -1를 리턴하여 f>=0 이 될 수 없어 Mike Found를 출력하지 않는다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함