package com.codemonkey;
import static java.lang.System.err;
import static java.lang.System.out;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Main{
public static void main(String[] args){
demoCollections();
}
public static void demoCollections(){
List<Agua> listaAgua = new ArrayList<>(Arrays.asList(new Agua(2,"Z"),new Agua(7,"X"), new Agua(new Integer("3"),"Q")));
out.println(listaAgua);//lista no ordenada
Collections.sort(listaAgua);//se orden lista
out.println(listaAgua);//lista ordenada
}
}
class Agua implements Comparator<Agua>, Comparable<Agua>{
private int fuente;
private String valor;
public Agua(){}
public Agua(int fuente, String valor){
this.fuente=fuente;
this.valor=valor;
}
public int getFuente(){
return fuente;
}
public void setFuente(int fuente){
this.fuente=fuente;
}
public String getValor(){
return valor;
}
public void setValor(String valor){
this.valor=valor;
}
@Override
public String toString(){
if(this.fuente < 0 && this.valor == null){
return "Agua{}";
}
return "Agua{fuente:"+fuente+", valor:"+valor+"}";
}
@Override
public int compare(Agua a, Agua a1) {
return a.fuente - a1.fuente;
}
public int compareTo(Agua a) {
return (this.valor).compareTo(a.valor);
}
}
Ejemplo Collections Java
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.