2012-03-26 2 views
0
Stack<?>[] stacks = { 
    new Stack<Bed>(), 
    new Stack<Bookshelves>(), 
    new Stack<Chair>(), 
    new Stack<Desk>(), 
    new Stack<Table>() 
}; 

스택 배열을 만드는 코드입니다. 내가 배열에 넣는 이유는 그것이 과제의 요구 사항 중 하나이기 때문입니다. 프로그램은 배열없이 작동합니다.JAVA 와일드 카드 캡쳐 오류로 제네릭 스택 배열이 잘못되었습니다.

또한 Stack은 자신의 Stack (과제의 요구 사항)을 만들어야했기 때문에 제네릭을 사용합니다.

while(sc.hasNext()){ 
    temp = sc.nextLine().split(" "); 
    if(temp[0].equals("Bed")){ 
     //beds.push(new Bed(temp[1], temp[2])); 
     stacks[0].push(new Bed(temp[1], temp[2])); 
    }else if(temp[0].equals("Table")){ 
     //tables.push(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4])); 
     stacks[4].push(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4])); 
    }else if(temp[0].equals("Desk")){ 
     //desks.push(new Desk(temp[1],temp[2], Integer.parseInt(temp[3]), Integer.parseInt(temp[4]))); 
     stacks[3].push(new Desk(temp[1],temp[2], Integer.parseInt(temp[3]), Integer.parseInt(temp[4]))); 
    }else if(temp[0].equals("Chair")){ 
     //chairs.push(new Chair(temp[1], temp[2])); 
     stacks[2].push(new Chair(temp[1], temp[2])); 
    }else if(temp[0].equals("Bookshelves")){ 
     //bookshelves.push(new Bookshelves(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), temp[5])); 
     stacks[1].push(new Bookshelves(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), temp[5])); 
    }else{ 
     color = temp[0]; 
    } 
} 

이 코드는 텍스트 파일에서 정보를 가져 와서 개체를 스택에 푸시합니다.

push(capture#627 of ?) in Stack<capture#627 of ?> cannot be applied to (Bed) 

이 오류는 내가 만든 모든 클래스에 대해 반복 :

나는 오류가 말을 얻을.

주석 처리 된 부분은 각 객체에 대해 단일 스택을 만들 때 이전에 작동했던 코드입니다.

불필요한 중간 변수에 대한 점을 빼앗기 때문에 모든 것을 스택에 푸시 한 후 배열에 모든 것을 넣을 수 없습니다.

답변

2

유일한 방법은 적절 이렇게 입력-안전하게되는 하나

a)는 전부가 Furniture 확장 클래스)

b) 각각의 스택에 대해 별도의 변수를 유지 가정 한 Stack<Furniture> (이것을 결합 배열을 완전히 제거하십시오.

+0

시도했지만 작동하지 않았습니다. 또한 'b'옵션을 지정하는 것은 할당에 허용되지 않습니다. – prunes4u

+0

나는 이것들이 적절하게 또는 안전하게 형용 할 수있는 유일한 방법이라고 말했을 때 그것을 의미했다. 대안은 타입 안전을 잃고 안전하지 않은 원시 캐스트를 시작하는 것입니다 :'(Stack) stacks [0] .push'는'Object'를 취합니다. 어쨌든. –

+2

그래, 왜 임무가 이것을 요구하는지 모르겠다. 가난한 디자인을 가르치는 것처럼 보입니다. –

1

시험해보세요.

((Stack<Bed>)stacks[0]).push(new Bed(temp[1], temp[2]));