2013-08-03 5 views
7

정수 및 문자열을 포함해야하는 Arraylist를 만들고 싶습니다. 가능합니까?정수 및 문자열을 포함하는 Arraylist

ArrayList<Integer> intList=new ArrayList<Integer>(); 
    intList.add(1); 
    intList.add(2); 

ArrayList<String> strList=new ArrayList<String>(); 
    strList.add("India"); 
    strList.add("USA"); 
    strList.add("Canada"); 

나는 새로운 ArrayList를로 IntList를 & strList를 넣을 : 아래로

나는 두 개의 ArrayList를 만들었습니다.

그럴 수 있습니까 ?? 그렇다면, 어떻게?

+6

그래, 당신은'ArrayList '을 만들 수있다.하지만, 내 충고는 이것이다 : do not. 유형이 다른 혼합형 목록을 만들지 마십시오. 이는 프로그램 디자인이 손상되어이 종류의 몬스터가 필요하지 않도록 개선해야한다는 것을 의미합니다. –

+2

왜 단일 ArrayList에서 두 가지 유형을 혼합하고 싶습니까? –

+0

이 두 목록간에 종속성이 있습니까? –

답변

7

를 검색하는 동안 개체를 확인

.

List<List> listOfMixedTypes = new ArrayList<List>(); 

ArrayList<String> listOfStrings = new ArrayList<String>(); 
ArrayList<Integer> listOfIntegers = new ArrayList<Integer>(); 

listOfMixedTypes.add(listOfStrings); 
listOfMixedTypes.add(listOfIntegers); 

하지만, 더 좋은 방법은 컴파일러가 더 이상 정수 목록에 캐릭터를 넣어 같은 종류의 혼합에서 당신을 방지 할 수 없을 것이기 때문에 두 목록을 추적하기 위해 Map 사용하는 것입니다. Either<A, B>Left<A, B> 또는 Right<A, B> 중 하나입니다 :

Map<String, List> mapOfLists = new HashMap<String, List>(); 

mapOfLists.put("strings", listOfStrings); 
mapOfLists.put("integers", listOfIntegers); 

mapOfLists.get("strings").add("value"); 
mapOfLists.get("integers").add(new Integer(10)); 
+1

원시 유형 = 불량 – newacct

5

피할 수없는 경우이 개체 유형 목록을 사용하지 마십시오. 개별 목록을 찾으십시오.

다음 모든 유형의 개체를 받아 Object

List<Object> list = new ArrayList<Object>(); 

의 유형에 대한 이동하지만, 검색하는 동안 돌봐해야하지합니다. 그러나 목록 컨테이너의 제네릭에 포기해야 다음과 같이이 작업을 수행 할 수

for (Object obj: list) { 
    if (obj instanceof String){ 
     // this is string 
    } else if (obj instanceof Integer) { 
     // this is Integer 
    } 
} 
2
List<Object> oList=new ArrayList<Object>(); 
+1

나는 왜 당신이 그렇게 화를 내는지 이해할 수 없다? 그는 단지 질문을하고있다. 나는 올바른 답을 준다.이 솔루션의 위험한면은 또 다른 문제이다. –

+0

나는 화를 내고 있지 않습니다. 그러나 나는 대답으로 주어진 나쁜 조언을 싫어합니다. –

2

당신은 태그 합 유형를 사용할 수 있습니다.

public interface Either<A, B>; 
public class Left<A, B> implements Either<A, B> { 
    public final A value; 
    public Left(A value) { 
    this.value = value; 
    } 
} 
public class Right<A, B> implements Either<A, B> { 
    public final B value; 
    public Right(B value) { 
    this.value = value; 
    } 
} 

그래서, 당신은 ArrayList<Either<Integer, String>>를 사용할 수 있습니다처럼 자바에서 그것을 볼 것이다.

for (Either<Integer, String> either : intsOrStrings) { 
    if (either instanceof Left) { 
    Integer i = ((Left<Integer, String>) either).value; 
    } else if (either instanceof Right) { 
    String s = ((Right<Integer, String>) either).value; 
    } 
} 

이 방법은 Object을 사용하는 것보다 더 안전합니다.

관련 문제