2012-03-07 2 views
1

ArrayList에만 적용되지 않았습니다. 배열 및 2D 배열. 내가해야 할 일은 다른 클래스의 ArrayList에서 읽을 수 있어야한다는 것입니다. 주요 목표는 for 루프에서 읽은 다음 항목에 표시되는 값을 사용하는 것입니다. 그러나, 나는 그것을 테스트하고 내 코드 다음Java - 다른 클래스의 ArrayList에서 읽기

import java.util.ArrayList; 

public class Main 
{ 
    public static void Main() 
    { 
     System.out.println("Test"); 
     ArrayList <Objects> xcoords = new ArrayList<Objects>(); 

     for(int x = 1 ; x < xcoords.size() ; x++) 
     { 
      System.out.println(xcoords.get(x)); 
     } 
    } 
} 

그리고 클래스를이 오류 여기

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 
    at java.util.ArrayList.rangeCheck(ArrayList.java:604) 
    at java.util.ArrayList.get(ArrayList.java:382) 
    at Main.Main(Main.java:14) 

입니다 점점 ​​계속이 빠른 프로그램을 한 곳의 ArrayList는

import java.util.ArrayList; 

public class Objects 
{ 
    public void xco() 
    { 
     ArrayList xcoords = new ArrayList(); 
     //X coords 
     //Destroyable 
     xcoords.add(5); 
     xcoords.add(25); 
     xcoords.add(5); 
     xcoords.add(5); 
     xcoords.add(25); 
     xcoords.add(5); 
     //Static Walls 
     xcoords.add(600); 
     xcoords.add(400); 
     xcoords.add(600); 
    } 
} 

입니다 누군가가 올바른 방향으로 나를 가리킬 수 있다면 그것은 매우 가치있을 것입니다. 그러나 디버깅을 시도했지만 도움이되는 모든 것을 얻을 수 있습니다.

미리 감사드립니다.

+0

이는 배열에서도 작동하지 않습니다. 저는 여러분이 객체 나 메소드가 어떻게 작동하는지, 또는 가변 스코프가 무엇인지 파악하지 못했습니다. 그 외에, 위의 코드는'size()'가'0'을 리턴 할 때 예외를 throw하지 않습니다. –

+0

좋아, 그럼 어떻게할까요? 내가 모든 사람이 실수하는 걸 배울 뿐이라는 것을 명심해라. – Kyle93

답변

6

엄밀히 말하자면, 0 요소가있는 ArrayList의 색인 위치 1 때문입니다. 루프 인덱스 변수 x에 대한 시작 위치를주의하십시오. 새로운에

ArrayList <Objects> xcoords = new ArrayList<Objects>(); 

xcoords 점, 빈 ArrayList하지 당신은 클래스 개체에서 만든 하나 :하지만이 라인을 고려하십시오.ArrayList, 당신의 main 방법으로, 다음

public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList 
    ArrayList<Integer> xcoords = new ArrayList<Integer>(); 

    // .. add all the elements .. 

    return xcoords; 
} 

같은 방법 xco을 변경 것을 얻으려면

public static void main(String [] args) { // add correct arguments 

    //.. 
    ArrayList <Integer> xcoords = (new Objects()).xco(); 

    for(int x = 0 ; x < xcoords.size() ; x++) { // start from index 0 
     System.out.println(xcoords.get(x)); 
    } 
} 
+0

고맙습니다. 그렇게 말했을 때 정말 감사합니다. . 나는 그것을 완전히 이해했음을 확인하기 위해 몇 가지 다른 것들을 시도 할 것이지만, 다시 한번 감사드립니다! – Kyle93

3

여기서 두 개의 완전히 관련없는 목록을 만들면됩니다. 배열 목록을 Objects 클래스의 속성으로 가져 와서 인스턴스 메서드를 통해 가져 오거나 인스턴스 또는 정적 메서드에서 반환하거나 속성을 정적으로 만듭니다. IMO는 대부분의 상황에서 처음 두 가지가 바람직합니다.

public class Objects { 
    public static List<Integer> getXcoords() { 
     List<Integer> xcoords = new ArrayList<Integer>(); 

     // Your same code, but adding: 
     return xoords; 
    } 
} 

는 다음을 사용 : 또한, 귀하의 ListInteger이어야

import java.util.ArrayList; 

public class Main { 
    // Note the lower-case "main" here. You want that. 
    public static void main() { 
     List<Integer> xcoords = Objects.getXcoords(); 
     // etc. 

하지 Objects의, Objects의 인스턴스를 들고 컬렉션을 만들 것이다. 한 걸음 뒤로 물러나 더 좋은 방법으로 배열을 배열과 연관시킬 수 있습니다. Objects 배열을 만들지 않겠습니까? 아니요. 배열은 int 또는 Integer입니다.

또한 Arrays.asList이 있습니다.

+0

@BrianRoach 그래, 벌써 - 많은 붙여 넣기에 충분하지 않은 컷. –

+0

정말 고맙습니다. 당신과 파 줄리는 매우 도움이되었지만, 조금 더 쉽게 이해할 수있는 방법으로 설명했습니다. 마지막으로 객체 배열에 대한 마지막 문장이 매우 좋았습니다. 다시 한번 감사드립니다! 또한 내가 당신의 포스트를 '+'할 수 있다면 나는 rep에 기댈 수 있습니다 :/할 수있을 때, 다시 한번 고마워요 – Kyle93

1

당신은 당신이 배열의 요소에 액세스하려고하는 것을 의미 IndexOutOfBoundsException이있는 존재하지 않습니다.

여기에 게시 된 코드에서 배열은 전혀 액세스하지 않습니다 (목록이 비어있어 for 루프가 한 번 실행되지 않습니다). 즉 예외가 다른 곳에서 발생합니다.

그러나 코드도 의미가 없습니다.가능한 한 코드에 가깝게 머무르는 동안 리팩터링 했으므로 작동 방법을 볼 수 있습니다.

public static void main(String[] args){ 
    Objects myObjects = new Objects(); 
    ArrayList<Integer> listFromMyObjects = myObjects.getList(); 
    for(int x = 0 ; x < listFromMyObjects.size() ; x++) 
    { 
     System.out.println(listFromMyObjects.get(x)); 
    } 
} 


public class Objects 
{ 
    private ArrayList<Integer> myList; 

    public Objects(){ 
     myList = new ArrayList<Integer>(); 
     myList.add(5); 
     myList.add(25); 
     myList.add(5); 
     myList.add(5); 
     myList.add(25); 
     myList.add(5); 
     myList.add(600); 
     myList.add(400); 
     myList.add(600); 
    } 

    public ArrayList<Integer> getList(){ 
     return myList; 
    } 
} 
+0

답변 해 주셔서 감사합니다! 다시 한 번 다른 대답을 통해 나는 더 나은 이해가 없으며 내가 잘못 된 이유를 알 수 있습니다. 지금은 많은 의미가 있습니다. 감사합니다. – Kyle93

관련 문제