Compare two objects ASC and DESC by 2 fields using Comparable - java

I want to compare two objects of a class that implements Comparable, I need to compare the objects using two java.sql.Time Objects ASC and DESC, I sort them in mysql like this:
...order by startTime ASC, endTime DESC
and I need to sort them in java in the same way, but im using just:
#Override
public int compareTo(Cita o) {
return (getHoraInicio().compareTo(o.getHoraInicio()));
}
but I dont know how to sort them with two fields like mysql, ASC and DESC.
this is the full implementation of the class I want to sort.
import java.text.SimpleDateFormat;
import java.sql.Time;
public class Cita implements Comparable<Cita> {
public Time horaInicio;
public Time horaTermino;
public Paciente paciente;
public String actividad;
public String observacion;
public String recordar;
public String ciudad;
public String TipoCita;
public String fecha;
public int idPaciente;
public int idCita;
public Cita() {
}
public Cita(String fecha, Time horaInicio, Time horaTermino, int idPaciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.idPaciente = idPaciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
public Cita(int idCita, String fecha, Time horaInicio, Time horaTermino, Paciente paciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.idCita = idCita;
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.paciente = paciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
#Override
public int compareTo(Cita o) {
return (getHoraInicio().compareTo(o.getHoraInicio()));
}
public int getIdCita() {
return idCita;
}
public void setIdCita(int idCita) {
this.idCita = idCita;
}
public Time getHoraInicio() {
return horaInicio;
}
public void setHoraInicio(Time horaInicio) {
this.horaInicio = horaInicio;
}
public Time getHoraTermino() {
return horaTermino;
}
public void setHoraTermino(Time horaTermino) {
this.horaTermino = horaTermino;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public String getActividad() {
return actividad;
}
public void setActividad(String actividad) {
this.actividad = actividad;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public String getRecordar() {
return recordar;
}
public void setRecordar(String recordar) {
this.recordar = recordar;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getTipoCita() {
return TipoCita;
}
public void setTipoCita(String TipoCita) {
this.TipoCita = TipoCita;
}
public int getIdPaciente() {
return idPaciente;
}
public void setIdPaciente(int idPaciente) {
this.idPaciente = idPaciente;
}
#Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + this.idCita;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cita other = (Cita) obj;
if (this.idCita != other.idCita) {
return false;
}
return true;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
#Override
public String toString() {
SimpleDateFormat formatohora = new SimpleDateFormat("h:mm");
return formatohora.format(horaInicio) + " - " + formatohora.format(horaTermino) + ", " + paciente.getNombre();
}
}

On tie do the compare using the "other" object as a your left-hand-side operand (effectively reversing the order). You could also do a normal compare on end times and negate the answer.
#Override
public int compareTo(Cita o) {
int asc = getHoraInicio().compareTo(o.getHoraInicio());
if (asc != 0) { return asc; }
return o.getHoraTermino.compareTo(getHoraTermino())
}
Note, I am assuming HoraTermino maps to endTime.

Related

How to get number of different words in Java?

I am working with Musical Jukebox program. I have two main classes: Song.java and Playlist.java. The Song.java is as follows:
public class Song {
String name;
String title;
double length;
public Song(String name,String title,double length)
{
this.name=name;
this.title=title;
this.length=length;
}
public void setArtist(String songname)
{
name=songname;
}
public String getArtist()
{
return name;
}
public void setTitle(String songtitle)
{
title=songtitle;
}
public String getTitle()
{
return title;
}
public void setLength(double songlength)
{
length=songlength;
}
public double getLength()
{
return length;
}
public String toString()
{
return "Title: " + getTitle() + ", Artist: " + getArtist()
+ ", Track Length: " + getLength();
}
And Playlist.java is as follows:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
#SuppressWarnings("serial")
public class Playlist<E extends Song> extends java.util.Vector<E> {
java.util.Iterator<E> itr = this.iterator();
String name;
ArrayList<Song> songList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Song> getSongList() {
return songList;
}
public void setSongList(ArrayList<Song> songList) {
this.songList = songList;
}
public void PlayList() {
name = "Untitled";
songList = new ArrayList<Song>();
}
public Playlist(String name) {
this.name = name;
songList = new ArrayList<Song>();
}
public Object getTitle()
{
return "Playlist Title";
}
public boolean addtoPlist(Song song1) {
songList.add(song1);
return true;
}
public Song getSong(int index) {
songList.trimToSize();
if(songList.size() >= index){
return songList.get(index);
}
else
return null;
}
public boolean hasTitle(String string) {
if( string.equals("Playlist Title"))
return true;
return false;
}
public boolean hasArtist(String string) {
if(string.equalsIgnoreCase("artist1"))
return true;
return false;
}
public Object numberOfSongs() {
// TODO Auto-generated method stub
return songList.size();
}
public Object numberOfArtists()
{
return 0;
}
public Object numberOfTitles()
{
return null;
}
public double playTime() {
return 0;
}
public Object findSong(Song song1) {
if(song1.equals("song1")&&song1.equals("song2")&&
song1.equals("song3")&&song1.equals("song4"))
itr.next();
return true;
}
public void sortByArtist()
{
}
public boolean removeFromPlist(Song str) {
songList.remove(str);
return true;
}
}
And this is playlisttest.java for unit testing:
import junit.framework.TestCase;
import java.util.Vector;
public class PlaylistTest extends TestCase {
private Playlist<Song> aPlaylist;
private Song song1, song2, song3, song4, duplicate_song, nullSong;
public void setUp() {
aPlaylist= new Playlist<Song>("Playlist Title");
song1 = new Song("Artist1", "AA", 6.00);
song2 = new Song("Artist1", "BB", 3.50);
song3 = new Song("Artist2", "BB", 3.00);
song4 = new Song("Artist2", "CC", 5.50);
duplicate_song = new Song("ARTIST1", "TITLE1", 5.00); // Same song with song 1
nullSong = null;
}
protected void tearDown() throws Exception
{
super.tearDown();
}
protected void fillPlaylist() {
aPlaylist.addtoPlist(song1);
aPlaylist.addtoPlist(song2);
aPlaylist.addtoPlist(song3);
aPlaylist.addtoPlist(song4);
}
public void test_Constructor() {
assertNotNull(aPlaylist);
assertTrue(aPlaylist instanceof Vector);
assertTrue(aPlaylist.isEmpty());
}
public void test_getTitle() {
assertTrue(aPlaylist.getTitle().equals("Playlist Title"));
}
public void test_addtoPList() {
assertTrue(aPlaylist.isEmpty());
assertTrue(aPlaylist.addtoPlist(song1));
assertEquals(1, aPlaylist.size());
assertTrue(aPlaylist.addtoPlist(song2));
assertTrue(aPlaylist.addtoPlist(song3));
assertEquals(3, aPlaylist.size());
assertFalse(aPlaylist.addtoPlist(nullSong));
assertEquals(3, aPlaylist.size());
assertFalse(aPlaylist.addtoPlist(duplicate_song));
assertEquals(3, aPlaylist.size());
}
public void test_removeSong() {
fillPlaylist();
int size = aPlaylist.size();
assertFalse(aPlaylist.removeFromPlist(nullSong));
assertEquals(size, aPlaylist.size());
assertFalse(aPlaylist.removeFromPlist(new Song("Artist1", "Title1", 1.00)));
assertEquals(size, aPlaylist.size());
assertTrue(aPlaylist.contains(duplicate_song));
assertTrue(aPlaylist.removeFromPlist(duplicate_song)); // Removing "duplicate_song" is removing "song1"
assertEquals(size - 1, aPlaylist.size());
}
public void test_getSong() {
fillPlaylist();
assertTrue(aPlaylist.getSong(0) instanceof Song);
assertEquals(song1, aPlaylist.getSong(0));
assertEquals(duplicate_song, aPlaylist.getSong(0));
assertEquals(song2, aPlaylist.getSong(1));
assertEquals(song3, aPlaylist.getSong(2));
assertEquals(song4, aPlaylist.getSong(3));
}
public void test_hasTitle() {
fillPlaylist();
assertTrue(aPlaylist.hasTitle("Playlist Title"));
assertFalse(aPlaylist.hasTitle("wrong title"));
}
public void test_hasArtist() {
fillPlaylist();
assertTrue(aPlaylist.hasArtist("artist1"));
assertFalse(aPlaylist.hasArtist("wrong artist"));
}
public void test_numberOfSongs() {
fillPlaylist();
assertEquals(4, aPlaylist.numberOfSongs());
}
public void test_numberOfArtists() {
fillPlaylist();
assertEquals(2, aPlaylist.numberOfArtists());
}
public void test_numberOfTitles() {
fillPlaylist();
assertEquals(3, aPlaylist.numberOfTitles());
}
public void test_playTime() {
fillPlaylist();
assertTrue(aPlaylist.playTime() == 19.00);
}
public void test_findElement() {
fillPlaylist();
assertEquals(0, aPlaylist.findSong(song1));
assertEquals(1, aPlaylist.findSong(song2));
assertEquals(2, aPlaylist.findSong(song3));
assertEquals(3, aPlaylist.findSong(song4));
//assertEquals(-1, aPlaylist.findSong(new Song("Not", "There", 0)));
}
public void test_sortByArtist() {
// TODO: Assignment 6 -- create new test case here: sort by artist
}
public void test_sortByTitle() {
}
}
I would like to implement numberOfTitles method that retrieves number of different titles but I really do not know how to take different titles and return the count (which is 3 in our case as it could be seen).If possible could you help me to solve this please? Your help is greatly appreciated!
You can store the unique titles in a Set and get the size of this once you're done:
Set<String> uniqueSongs = new Set<>();
for (Song song : songList)
{
uniqueSongs.add(song.getTitle());
}
Then you can use uniqueSongs.size() to get the number of unique songs.
You can also use streams if you're in Java 8 (thanks to Boris the Spider for pointing it out):
Set<String> uniqueSongs = songList.stream().map(Song::getTitle).collect(Collectors.toS‌​et())

using Adjacency list structure for directed graph java

I have problem to implement the transpose of a graph using only Adjacency List, without Edge List. Every vertex of the graph has a positional list that stores adjacent vertexes. When you have to transpose the graph, every element stored in a list of a vertex A, has to be removed and used as a source vertex. So if we have the situation
A -> B
B after its removal, add to its own adjacent list the old source Vertex A
We have as result:
B -> A
when I update the lists, i override the last information stored in, so I lose connection between vertexes.
public class Vertice implements Comparable<Vertice>{
public Vertice(int valore){
this.valore = valore;
this.color = Color.WHITE;
this.distanza = 0;
this.padre = null;
adiacenze = new NodePositionList<Vertice>();
}
public int getValore() {
return valore;
}
public void setValore(int valore) {
this.valore = valore;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position<Vertice> getPadre() {
return padre;
}
public void setPadre(Position<Vertice> padre) {
this.padre = padre;
}
public int getDistanza() {
return distanza;
}
public void setDistanza(int distanza) {
this.distanza = distanza;
}
public enum Color{
BLACK, WHITE, GREY;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("v_" + valore );
return sb.toString();
}
public boolean equals(Vertice v){
return this.compareTo(v) == 0;
}
#Override
public int compareTo(Vertice o) {
return this.valore - o.getValore();
}
public int getFin() {
return fin;
}
public void setFin(int fin) {
this.fin = fin;
}
public Position<Vertice> getRiferimentoVertice() {
return riferimentoVertice;
}
public void setRiferimentoVertice(Position<Vertice> riferimentoVertice) {
this.riferimentoVertice = riferimentoVertice;
}
public Iterable<Vertice> getAdiacenze() {
return adiacenze;
}
public void setAdiacenze(NodePositionList<Vertice> adiacenze) {
this.adiacenze = adiacenze;
}
public Position<Vertice> addNodoAdiacente(Vertice v){
Position<Vertice> newVertice = adiacenze.addLast(v);
v.setRiferimentoAsAdiacenza(newVertice);
return newVertice;
}
public Position<Vertice> removeNodoAdiacente(Position<Vertice> v){
return adiacenze.remove(v);
}
public Position<Vertice> getRiferimentoAsAdiacenza() {
return riferimentoAsAdiacenza;
}
public void setRiferimentoAsAdiacenza(Position<Vertice> riferimentoAsAdiacenza) {
this.riferimentoAsAdiacenza = riferimentoAsAdiacenza;
}
public boolean hasAdiacent(){
return adiacenze.size() == 0;
}
public boolean hasRedEdge(){
return redEdge;
}
public void setHasRedEdge(boolean redEdge){
this.redEdge = redEdge;
}
private boolean redEdge;
private int valore;
private Color color;
private Position<Vertice> padre;
private int distanza;
private int fin;
private Position<Vertice> riferimentoVertice;
private Position<Vertice> riferimentoAsAdiacenza;
private NodePositionList<Vertice> adiacenze;
here the "Grafo.java" class
public class Grafo {
public Grafo(int numV){
verticiGrafo = new NodePositionList<Vertice>();
listaArchi = new NodePositionList<Arco>();
this.V = numV;
}
public Position<Vertice> addVertice(Vertice v){
Position<Vertice> newAdded = verticiGrafo.addLast(v);
v.setRiferimentoVertice(newAdded);
return newAdded;
}
public NodePositionList<Vertice> getVertici(){
return verticiGrafo;
}
public Position<Arco> addArco(Arco a){
a.getSorgente().element().addNodoAdiacente(a.getDestinazione().element());
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> connect(Position<Vertice> sorgente, Position<Vertice> destinazione){
Arco a = new Arco(sorgente, destinazione);
Vertice v_sorgente = sorgente.element();
Vertice v_destinazione = destinazione.element();
v_sorgente.addNodoAdiacente(v_destinazione);
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> removeArco(Position<Arco> a){
a.element().getSorgente().element().removeNodoAdiacente(a.element().getDestinazione());
return listaArchi.remove(a);
}
public Iterable<Arco> archi(){
return listaArchi;
}
public void invertiArco(Position<Arco> a){
Arco a1 = a.element();
Position<Vertice> temp = a1.getDestinazione();
a1.setDestinazione(a1.getSorgente());
a1.setSorgente(temp);
Vertice sorgente = a1.getSorgente().element();
Vertice destinatario = a1.getDestinazione().element();
sorgente.addNodoAdiacente(destinatario);
}
public Position<Arco> getArcoByVertici(Position<Vertice> sorgente, Position<Vertice> destinazione){
for(Arco a: listaArchi){
if(a.getColor() == EdgeColor.NONE){
Vertice dest = a.getDestinazione().element();
Vertice sorg = a.getSorgente().element();
if(sorg.equals(sorgente.element()) && dest.equals(destinazione.element())){
return a.getRiferimentoArco();
}
}
}
return null;
}
public void removeAllAdiacenze(){
for(Vertice v: this.getVertici()){
v.setAdiacenze( new NodePositionList<Vertice>());
}
}
public void setColorArco(Position<Arco> a, EdgeColor ec){
a.element().setColor(ec);
}
public NodePositionList<Arco> getListaArchi() {
return listaArchi;
}
public void setListaArchi(NodePositionList<Arco> listaArchi) {
this.listaArchi = listaArchi;
}
private NodePositionList<Vertice> verticiGrafo;
private NodePositionList<Arco> listaArchi; //lista archi uscenti
public final int V;
}
here the method on the "Ricerca.java" class that I'm trying to make
public static Grafo traspostaGrafo(Grafo g){
NodePositionList<Vertice> npl = g.getVertici();
Position<Vertice> u = npl.first();
while (u != npl.getTail()){
u.element().setColor(Color.WHITE);
NodePositionList<Vertice> adiacenti = g.getListaAdiacenti(u.element().getValore());
Position<Vertice> adiacente = adiacenti.first();
while (adiacente != adiacenti.getTail() && adiacente.element().getFlag() == 0){
g.addNodoAdiacente(adiacente.element(), u.element());
g.removeNodoAdiacente(adiacente);
adiacente = adiacenti.next(adiacente);
u.element().setFlag(1);
}
}
return g
}

how to sort linkedhashmap based on key . Here I used an object as a key

I am using the linked hashmap to populate values in expandable list .I successfully populate them. Here key is the menuitems and values are corresponding modifiers I places two buttons foe increasing and decreasing quantity of menu items .As it is the key I remove them and update them and again I put them in the list. This time they are inserting on the lastrow . How to placethem in same position as they were before deletion?
The function where i update my key.
public void putminusquantity(int pos)
{
try
{
SaleDetailsMenuItems aa = (SaleDetailsMenuItems)listDataChild.keySet().toArray()[pos];
List<ModifList> modlist =listDataChild.get(aa);
//modlist.add(mli);
listDataChild.remove(aa);
int qty = Integer.parseInt(aa.getQuantity());
float priced = Float.parseFloat(aa.getPrice());
//Double finaltotal1 = Math.round( priced * 100.0 ) / 100.0;
//Toast.makeText(getApplicationContext(), finaltotal1.toString(), Toast.LENGTH_SHORT).show();
System.out.println(qty);
float priced1 = priced / qty;
if(qty>1)
{
qty--;
priced = priced1 * qty;
String quantity1 = Integer.toString(qty);
String price1 = Float.toString(priced);
aa.setQuantity(quantity1);
aa.setPrice(price1);
listDataChild.put(aa, modlist);
listviewAdapter = new ExpandableListAdapter(getApplicationContext(), listDataChild);
list.setAdapter(listviewAdapter);
listviewAdapter.notifyDataSetChanged();
resetquantity();
settotal();
}
else
{
Toast.makeText(getApplicationContext(), "Invalid Quantity", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
Here is the model class:
class SaleDetailsMenuItems extends Sale
{
int i;
private int id;
private String name;
private String price;
private String quantity;
private int statuss;
private String itemnote;
private long saledetailId;
private long saleid;
private int menutype;
private long menu_id;
private int istaxinclusive;
private int coursing_id;
private String seatname;
private int seatId;
private String reason;
// private int discountdtls;
private int istaxexmpt;
private float taxpercent;
//private float inctaxpercent;
private float taxamt;
private float incltaxamt;
private int ordertype;
private boolean istaxincl;
private int storeid;
private int crtdby;
private int modby;
private int status;
public SaleDetailsMenuItems(int i1,String item, String quantity,
String price, int id, int statuss,String itemnote)
{
// TODO Auto-generated constructor stub
this.i=i1;
this.id=id;
this.name = item;
this.quantity = quantity;
this.price = price;
this.statuss = statuss;
this.itemnote = itemnote;
//this.flag = flag;
}
public int getStatuss() {
return statuss;
}
public void setStatuss(int statuss) {
this.statuss = statuss;
}
public long getSaledetailId() {
return saledetailId;
}
public void setSaledetailId(long saledetailId) {
this.saledetailId = saledetailId;
}
public long getSaleid() {
return saleid;
}
public void setSaleid(long saleid) {
this.saleid = saleid;
}
public int getMenutype() {
return menutype;
}
public void setMenutype(int menutype) {
this.menutype = menutype;
}
public long getMenu_id() {
return menu_id;
}
public void setMenu_id(long menu_id) {
this.menu_id = menu_id;
}
public int getIstaxinclusive() {
return istaxinclusive;
}
public void setIstaxinclusive(int istaxinclusive) {
this.istaxinclusive = istaxinclusive;
}
public int getCoursing_id() {
return coursing_id;
}
public void setCoursing_id(int coursing_id) {
this.coursing_id = coursing_id;
}
public String getSeatname() {
return seatname;
}
public void setSeatname(String seatname) {
this.seatname = seatname;
}
public int getSeatId() {
return seatId;
}
public void setSeatId(int seatId) {
this.seatId = seatId;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public int getIstaxexmpt() {
return istaxexmpt;
}
public void setIstaxexmpt(int istaxexmpt) {
this.istaxexmpt = istaxexmpt;
}
public float getTaxpercent() {
return taxpercent;
}
public void setTaxpercent(float taxpercent) {
this.taxpercent = taxpercent;
}
public float getTaxamt() {
return taxamt;
}
public void setTaxamt(float taxamt) {
this.taxamt = taxamt;
}
public float getIncltaxamt() {
return incltaxamt;
}
public void setIncltaxamt(float incltaxamt) {
this.incltaxamt = incltaxamt;
}
public int getOrdertype() {
return ordertype;
}
public void setOrdertype(int ordertype) {
this.ordertype = ordertype;
}
public boolean isIstaxincl() {
return istaxincl;
}
public void setIstaxincl(boolean istaxincl) {
this.istaxincl = istaxincl;
}
public int getStoreid() {
return storeid;
}
public void setStoreid(int storeid) {
this.storeid = storeid;
}
public int getCrtdby() {
return crtdby;
}
public void setCrtdby(int crtdby) {
this.crtdby = crtdby;
}
public int getModby() {
return modby;
}
public void setModby(int modby) {
this.modby = modby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStatus() {
return statuss;
}
public void setStatus(int statuss) {
this.statuss = statuss;
}
public String getItemnote() {
return itemnote;
}
public void setItemnote(String itemnote) {
this.itemnote = itemnote;
}
} I am using this class's object as key in my Map.
TreeMap
Is the way to sort the map by key. May be this will help you

Cannot cast to java.Lang.Comparable

I have two JFrames:
JFrameA have a JList with a cellrender to display Cita objects, and a JPopupMenu that trigger a JFrameB to set and remove elements from the JList.
public class JFrameA extends javax.swing.JInternalFrame {
public static DefaultListModel model = new DefaultListModel();
HashMap<Cita, Icon> elementos = new HashMap();
Cita cita;
//method to retrieve from DB the objects
private void fillJList(){
//create object to add to the model
while(rs.next()){
Cita = new Cita(rs.getTime("TimeColumn").....);
model.addElement(cita);
elementos.put(cita, aIcon);
}
jlistDia.setModel(model);
RenderJList render = new RenderJList(elementos);
JList.setCellRenderer(render);
}
JFrameB receive a Cita object to update it and set it to the model of the JFrameA
public class JFrameB extends javax.swing.JFrame {
Cita objectToModify;
public JFrameB(Cita objetToModify){
this.objectToModify=objectToModify;
}
private void updates(){
//get the new data of the object to set the JList of frameA
Cita updatedObject = new Cita();
JFrameA.model.set(objectToModify.getIndex(), updatedObject);
//JFrameA.model is updated with no problems, but I want to sort the Cita objects by a Time param.
sortModel(VistaDiaria.m);
}
private void sortModel(DefaultListModel model) {
List<Cita> list = new ArrayList<>();
for (int i = 0; i < model.size(); i++) {
list.add((Cita) model.get(i));
}
Collections.sort(list);
model.removeAllElements();
for (Cita s : list) {
model.addElement(s);
}
}
The method sortModel throw an ClassCastException and I don't know why, my Cita class implements Comparable this is the StackTrace i got.
java.lang.ClassCastException: expeDiente.Cita cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:316)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:184)
at java.util.Arrays.sort(Arrays.java:1244)
at java.util.Collections.sort(Collections.java:166)
Cita class:
import java.text.SimpleDateFormat;
import java.sql.Time;
public class Cita implements Comparable<Cita> {
public Time horaInicio;
public Time horaTermino;
public Paciente paciente;
public String actividad;
public String observacion;
public String recordar;
public String ciudad;
public String TipoCita;
public String fecha;
public int idPaciente;
public int idCita;
public Cita() {
}
public Cita(String fecha, Time horaInicio, Time horaTermino, int idPaciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.idPaciente = idPaciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
public Cita(int idCita, String fecha, Time horaInicio, Time horaTermino, Paciente paciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.idCita = idCita;
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.paciente = paciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
#Override
public int compareTo(Cita o) {
return (getHoraInicio().compareTo(o.getHoraInicio()));
}
public int getIdCita() {
return idCita;
}
public void setIdCita(int idCita) {
this.idCita = idCita;
}
public Time getHoraInicio() {
return horaInicio;
}
public void setHoraInicio(Time horaInicio) {
this.horaInicio = horaInicio;
}
public Time getHoraTermino() {
return horaTermino;
}
public void setHoraTermino(Time horaTermino) {
this.horaTermino = horaTermino;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public String getActividad() {
return actividad;
}
public void setActividad(String actividad) {
this.actividad = actividad;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public String getRecordar() {
return recordar;
}
public void setRecordar(String recordar) {
this.recordar = recordar;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getTipoCita() {
return TipoCita;
}
public void setTipoCita(String TipoCita) {
this.TipoCita = TipoCita;
}
public int getIdPaciente() {
return idPaciente;
}
public void setIdPaciente(int idPaciente) {
this.idPaciente = idPaciente;
}
#Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + this.idCita;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cita other = (Cita) obj;
if (this.idCita != other.idCita) {
return false;
}
return true;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
#Override
public String toString() {
SimpleDateFormat formatoInicio = new SimpleDateFormat("hh:mm");
SimpleDateFormat formatoTermino = new SimpleDateFormat("hh:mm aa");
return paciente.getNombre() + ", "
+ formatoInicio.format(horaInicio) + "-"
+ formatoTermino.format(horaTermino);
}
}
Your Cita class as shown here doesn't compile. So the compiled version that your other classes are seeing is not this one. If you can fix the compile errors in your Cita class, the other classes will start working OK too.
the definition used by the compiler wasnt the last implementation of my Cita class, I changed the name of the package and replaced the jar and the imports, and It works.

Java LinkedList with Object

Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}

Categories