2016-12-04 8 views
-2

일부 계산 지능 알고리즘을 사용하여 새로운 영역을 계획하고 있습니다.Arraylist.indexOf는 -1을 반환합니다.

이상한 이유로 특정 어레이의 색인을 찾을 때 문제가 있습니다.

예를 들어, 두 개의 배열, parentOne 및 parentTwo가 Integer 유형입니다. 1 300 배열 목록에 모두 300 임의의 정수 값을 추가합니다.

그런 다음 1-300 사이의 배열에서 임의로 선택된 인덱스 값을 검색하려고합니다. 예를 들어, 도시 수 있습니다 = 129, 그런 다음 코드는 parentOne의 인덱스 129로 이동하여 해당 위치에서 관련 값을 반환하지만 -1을 반환합니다. 어떤 도움을 크게 감상 할 수 < (35)

어떤 인덱스를 찾을 때

특이한 점은이 완벽하게 작동합니다!

감사합니다. ArrayList에의 indexOf 방법 -1을 반환하는 경우

private int[][] cycleCrossover(int first, int second){ 
    //tempArray to return 
    int[][] tempArray = new int[2][numberOfAreas]; 
    if(cycleCrossover == true){ 
     //select a random city 
     int selectedCity = 35;//random.nextInt(numberOfAreas); 
     int parentOneCity = 0; 
     int parentTwoIndex = 0; 
     int parentTwoCity = 0; 
     int parentOneIndex = 0; 
     int index = 0; 
     //used to store parent and exchange values as well as cycle 
     ArrayList<Integer> parentOne = new ArrayList<Integer>(); 
     ArrayList<Integer> parentTwo = new ArrayList<Integer>(); 
     ArrayList<Integer> cycle = new ArrayList<Integer>(); 

     //Assign values to the arrays 
     for(int i = 0; i <numberOfAreas; i++){ 
      parentOne.add(population[first][i]); 
      parentTwo.add(population[second][i]); 
     } 

     System.out.println(parentOne); 
     //get parentOne Cities into new array 
     long count = selectedCity; 
     //Determine my cycle contents 
     while(count > 0){ 
      //Get the index of the first city 
      index = parentOne.indexOf(selectedCity);   
      //Add the first cities index to my cycle 
      cycle.add(parentOne.indexOf(selectedCity)); 
      //add the next city to my parents cycle 
      selectedCity = parentTwo.get(index); 
      //take 1 from count 
      count = count - 1; 
     } 
} 
+1

'cycle.add (index)'가 더 깨끗하게 보입니다 ... 어쨌든. 분명히 35가 목록에 없거나 다른 값들 중 하나가된다. –

+0

오류는 분명하다.'parentOne' 목록에는 선택된 도시가 없다. 추가 했습니까? 그건 그렇고,'numberOfAreas'는 어디에 정의되어 있습니까? –

+0

'모집단'내용을 모른 채 도움을 받기가 어렵습니다. 제발 [mcve] 또는 디버거와 함께 코드를 통해 단계를 참조하십시오 –

답변

1

, 그것은 당신이 ArrayList에 존재하지 않는 내에서 검색하는 개체를 의미한다.

+0

고마워요 YWE, 내가 1 사이의 숫자를 생성 할 때 다른 변수를 사용하여 1-35 사이의 임의의 숫자를 생성했기 때문에 오류를 발견했다 -300 따라서, 인덱스는 35보다 큰 요소를 찾지 못했습니다. 감사합니다. – Coder1994UK