2017-04-09 1 views
-2

공용 클래스 자동차에 Comparable {어떻게 Java에서 ArrayBlockingQueue를 정렬 할 수 있습니까?

private String company, model; 
private int price; 


public Cars(String company, String model, int price){ 
    this.company=company; 
    this.model=model; 
    this.price=price; 
} 

@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + price; 
    return result; 
} 

@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    Cars other = (Cars) obj; 
    if (price != other.price) 
     return false; 
    return true; 
} 

public String toString(){ 
    return String.format("Comapany: %s, Model: %s, Price: %d", this.company, this.model, this.price); 
} 

public String getCompany() { 
    return company; 
} 


public void setCompany(String company) { 
    this.company = company; 
} 


public String getModel() { 
    return model; 
} 


public void setModel(String model) { 
    this.model = model; 
} 


public int getPrice() { 
    return price; 
} 


public void setPrice(int price) { 
    this.price = price; 
} 

public int compareTo(Object obj) { 


    return this.price-((Cars)obj).price; 
} 

}

공용 클래스 BlockingQueueExample {

BlockingQueue<Cars> queue; 
Random random=new Random(); 
private boolean running=false; 

public BlockingQueueExample(BlockingQueue<Cars> queue){ 
    this.queue=queue; 
    running=true; 
} 

public void producer() throws InterruptedException{ 

    while(running){ 
     int add_car=random.nextInt(5); 
     Cars value=null; 
     switch(add_car){ 
     case 0:value=new Cars("BMV", "q7", 4000);break; 
     case 1:value=new Cars("Renault","KWID", 2000);break; 
     case 2:value=new Cars("Porche","Cayenee", 3000);break; 
     case 3:value=new Cars("Skoda", "Rapid", 2500);break; 
     case 4:value=new Cars("Volkswagen", "Ameo", 3500);break; 
     } 

     queue.put(value); 
     System.out.println("PRODUCER "+ value); 
     System.out.println(); 
    } 
} 

public void consumer() throws InterruptedException{ 

    while(running){ 
     Thread.sleep(500); 
     if(random.nextInt(5)==0){ 
      Cars value=queue.take(); 
      //Collections.sort((List<Cars>) queue); 
      System.out.println("CONSUMER Taken value: "+value +", Queue size: "+queue.size()+"\n"+queue); 
      System.out.println(); 
     } 
    } 
} 

public void stop(){ 
    running=false; 
    // method to sort queue 
    System.out.println("Sorted queue:"+"\n"+queue); 
} 

}을 구현

내가 Arrays.sort에 (queue.toArray()) 컬렉션을 시도

.sort (큐), doesn; t wok; 내일을위한 프리젠 테이션을위한 것입니다 .... 누군가 pls welp

+1

우선 제목에 사용되는 언어가 필요하지 않습니다. 둘째로, 우리는 "용접"이 무엇을 의미하는지 모른다. 세 번째로,'ArrayBlockingQueue'는 FIFO 구조체이며, 정렬을위한 것이 아닙니다. –

답변

0

분명히 ArrayBlockingQueue을 정렬하는 것은 FIFO 디자인을 거스르는 것처럼 작동하지 않을 것입니다. Queue으로 정렬하려면 PriorityQueue을 사용해야합니다.

+0

그것도 시도해 보았습니다 (BlockingQueue queue = new PriorityBlockingQueue ....), didn; t 아무 것도 정렬하지 않았습니다 ... –

+0

@AndreiBratu'Cars' 클래스를 사용하기 위해 제네릭 타입을 정의 했습니까? 'BlockingQueue queue = new PriorityBlockingQueue <>();' –

+0

ye, 방금 배열에서 우선 순위로 바뀌 었습니다 ....하지만 여기에 내가해야 할 일이 있습니다 : 그래서 내 Cars 클래스는 hashcode, equals 및 compareTo를 구현해야합니다. 정렬 및 대기열 클래스에서 PriorityBlockingQueue 사용해야하며 Collections.sort 또는 Arrays.sort 사용하고 완료 한? –

0

BlockingQueue을 정렬 할 수 없지만 요소 배열을 정렬 할 수 있습니다.

당신은 거의 Arrays.sort(queue.toArray()) 시도를 했었습니다. 정렬되지 않은 대기열이 아니라 배열을 기억하고 인쇄해야합니다.

Cars[] arr = queue.toArray(new Cars[queue.size()]); 
Arrays.sort(arr); 
System.out.println("Sorted elements:\n" + Arrays.toString(arr)); 

관련없는

당신은 원시 일반적인 Comparable 사용할 수 없습니다. 이 값을 Comparable<Cars>으로 변경하십시오.

또한 정수 값을 빼서 compare() 값을 생성하면 오류가 발생합니다 (숫자 오버플로). 대신 Integer.compare()을 사용하십시오.

public class Cars implements Comparable<Cars> { 

    // lots of code 

    @Override 
    public int compareTo(Cars other) { 
     return Integer.compare(this.price, other.price); 
    } 
} 
+0

; Idonn : 자동차의 배열을 사용하려고하지만 BlockingQueue는 동시 패키지의 dat 구조이기 때문에 프레젠테이션을위한 스레드에서 예제가 필요합니다. D –

+0

['ArrayBlockingQueue]의 FIFO 특성을 원하지 않으면 '] (https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html)을 사용하려면 [PriorityBlockingQueue'] (https : // docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html)하지만 * iterating * 요소가 아니라 * 요소를 검색하기 위해서만 주문된다는 점에주의하십시오. * 제공된 Iterator는 특정 순서로'PriorityBlockingQueue' 요소를 순회하지 않습니다. * – Andreas

+0

... * 순서가 필요한 경우,'Arrays.sort (pq.toArray())'** (이 대답 참조) **를 사용해보십시오. 또한,'drainTo' 메소드는 우선 순위에 따라 일부 또는 모든 요소를 ​​제거하고 다른 콜렉션에 배치하는 데 사용할 수 있습니다. * – Andreas

관련 문제