2016-10-27 1 views
-3

특정 gpa에 대해 ExArrayList을 검색하고 싶습니까? ArrayList에 있으면 true 또는 false의 대답을 원합니다.항목에 대한 ArrayList를 검색하려면 어떻게해야합니까?

public class ExArrayList { 
     private String Name; 
     private double GPA; 

     public ExArrayList(String name, double gpa) { 
      this.Name = name; 
      this.GPA = gpa; 

     } 
     public void setGPA(double gpa) { 
      this.GPA = gpa; 
     } 

     public double getGPA() { 
      return GPA; 
     } 
     public void setName(String name) { 
      this.Name = name; 
     } 
     public String getName() { 
      return Name; 
     } 
     @Override 
     public String toString() { 
      return String.format("%s\t%f", this.Name, this.GPA); 
     } 
    } 

    public class Main { 
     public static void main(String[] args) { 

      ArrayList<ExArrayList> psy101 = new ArrayList<>(); 
      psy101.add(new ExArrayList("Bob", 2.9)); 
      psy101.add(new ExArrayList("Steve", 3.9)); 
      psy101.add(new ExArrayList("Charles", 4.0)); 

      System.out.println(); 
      System.out.printf("Student\tGPA\n"); 
      for(ExArrayList s : psy101) { 
       System.out.printf("%s\n", s); 

      } 

      boolean binFound = psy101.contains(2.9); // This is what I am using to search the ArrayList. It's not working. 
      System.out.println("Does the list contain GPA of 2.9? " +  binFound);` 
+2

정렬하고 덮어 쓸 필요가 –

+0

이진 검색 ['메소드의 개요 boolean equals (Object o)를'] (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html# equals-java.lang.Object-)뿐만 아니라 ['int hashCode()'] (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--) [ArrayList]에서 [''int indexOf (Object o)'를 사용하려면 (http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java .lang.Object-). – Turing85

답변

4

당신은 목록을 증기와 일치를 찾기 위해 람다를 사용할 수 있습니다 당신은 각 for 루프에서 비교해야 할

boolean binFound = psy101.stream().anyMatch(g -> g.getGPA() == 2.9); 
+0

이것은'Java 8' tho –

+0

@bradimus에서 작동합니다. 예제는 불필요한 자동 상자를 처리하며'anyMatch()'인수는 유효한 람다식이 아닙니다. – Andreas

0

. Java8 스트림없이

if(s.getGPA == 2.9){ 
     binFound = true; 
     break; 
    } 
+0

나는 프로그래밍에 익숙하지 않고 모든 의견/통찰력을 높이 평가한다. – datorre

+1

그건'자바 '에서 double을 비교하는 올바른 방법이 아닙니다. [this] (http : // stackoverflow.com/questions/179427/how-to-resolve-a-java-rounding-double-issue) 및 [this] (http://stackoverflow.com/questions/8081827/how-to-compare-two-double-values -in-java) –

+1

이 코드는 컴파일되지 않습니다. 's.getGPA'는 필드가 아니며 메서드입니다. – Turing85

0

:

boolean binFound = false; 
for(ExArrayList exArrayList : psy101) { 
     if(exArrayList.getGPA() == 2.9) { 
      binFound = true; 
      break; 
     } 
} 
System.out.println(binFound); 

Java8 스트림으로 :

boolean binFound = psy101.stream().map(ExArrayList::getGPA). 
anyMatch(gpa -> gpa == 2.9); 
System.out.println(binFound); 
-1

나는이 답변 중 하나를 좋아하지 않았다. 사람들은 doubles을 비교하려고 할 때 발생하는 정밀도 오류를 잊어 버렸습니다. 나는 많은 정밀도가 포함되어 있지 않기 때문에 그것이 GPA 목적에 너무 나쁘지 않아야한다는 것을 안다. 그러나, 일을하는 올바른 방법이나 올바른 방법이 있습니다. 설명을 위해 thisthis을 참조하십시오.

계획중인 작업을 올바르게 수행하는 방법은 바이너리 검색입니다. 하지만 먼저 목록을 정렬하여 작동시켜야합니다.

Java에서 개체를 정렬하는 방법은 무엇입니까? 먼저 자신의 가치를 비교하는 방법을 알아야하며이를 수행하는 몇 가지 방법이 있습니다. 예를 들어 Comparable을 사용합니다. 학습 목적으로 this을 확인하십시오.

사용 아무것도

import java.util.*; 
이제

, 개체에서 우리 implement Comparable 전에이 수입. 그것은 변경 한 후 다음과 같이 표시됩니다

public class ExArrayList implements Comparable<ExArrayList> { 
    private String Name; 
    private double GPA; 

    public ExArrayList(String name, double gpa) { 
     this.Name = name; 
     this.GPA = gpa; 

    } 
    public void setGPA(double gpa) { 
     this.GPA = gpa; 
    } 

    public double getGPA() { 
     return GPA; 
    } 
    public void setName(String name) { 
     this.Name = name; 
    } 
    public String getName() { 
     return Name; 
    } 
    @Override 
    public String toString() { 
     return String.format("%s\t%f", this.Name, this.GPA); 
    } 
    //new stuff needed to compare the objects 
    public int compareTo(ExArrayList other) {     
     return Double.compare(this.GPA, other.GPA);   
    } 
} 

이제 우리는 수행하여 목록을 정렬 할 수 있습니다 :

Collections.sort(psy101); 

그것을 정렬 후, 우리는 수행하여 객체의 인덱스를 검색 할 수 있습니다

//here we must pass a fake object with the value that we are trying to find 
int index = Collections.binarySearch(psy101, new ExArrayList(null, 2.9)); 

System.out.println(index >= 0 ? "True" : "False"); 

index은 목록에서 2.9의 위치를 ​​포함하며, 발견되지 않으면 음수를 포함합니다.

+0

downvote 할 계획이라면 먼저 코멘트를하십시오 –

관련 문제