2014-12-10 11 views
5

Sto scrivendo un programma di rubrica in java e devo elencare alfabeticamente le persone nell'elenco e per farlo ho bisogno di scrivere un algoritmo di ordinamento per un elenco in java e dovrebbe usare solo metodo compareTo(). Quindi qualcuno può aiutarmi a farlo?Ordinamento di una lista in ordine alfabetico utilizzando il metodo compareTo()

public void listAlpha() 
{ 
    Node tempNode = head; 

    for(int i = 0; i <= size; i++) 
     { 
      for(int j = 0; j <= i; j++) 
      { 
       int comparison = ((tempNode.getNext().getElement().getName()).compareTo(tempNode.getElement().getName())); 
       if(comparison < 0) 
       { 
        Person tempPerson = tempNode.getElement(); 

        tempNode.setElement(tempNode.getNext().getElement()); 
        tempNode.getNext().setElement(tempPerson); 
        tempNode = tempNode.getNext(); 
       } 
      } 


     } 

(Tra l'altro questo è un lavoro e sto usando le mie proprie strutture di dati.)

Questa è la classe che il metodo che ho scritto sopra appartiene:

import java.util.*; 

/** Singly linked list implementation .*/ 
public class SLinkedList<E> implements LinkedList<E>, Iterable<E> { 
    protected Node<E> head;  // head node of the list 
    protected Node<E> tail;  // tail node of the list 
    protected int size;  // number of nodes in the list 

    public Iterator<E> iterator() 
    { 
     return new LinkedListIterator(head); 
    } 

    /** Default constructor that creates an empty list */ 
    public SLinkedList() { 
    head = null; 
    tail = null; 
    size = 0; 
    } 

    public int size() { 
    return size; 
    } 

    public boolean isEmpty() { 
    return size == 0; 
    } 

    public void addFirst(E newElement) { 
    Node<E> newNode = new Node(newElement,null); 
    if(size == 0) //if list is empty 
     tail = newNode; 

    newNode.setNext(head); 
    head = newNode; 
    size++; 
    } 

    public void addLast(E newElement) { 
    Node<E> newNode = new Node(newElement,null); 

    if(size == 0) //if list is empty 
     head = newNode; 

    if (size != 0) //if list is not empty 
     tail.setNext(newNode); 

    tail = newNode; 
    size++; 
    } 

    public E removeFirst() { 
    Node<E> tempNode = null; 
    if (size != 0) { 
     if(size == 1) 
      tail = null; 

     tempNode = head; 
     head = head.getNext(); 
     tempNode.setNext(null); 
     size--; 
    } 

    //if list is empty then return null 
    return tempNode.getElement(); 

    } 

    public E removeLast() { 
    Node<E> tempNode = head; 

    if(size == 0) 
     return null; 

    if(size == 1) { 
     head = null; 
     tail = null; 
     size--; 
     return tempNode.getElement(); 
    } 

    //size is greater than 1 
    for(int i=1; i<=size-2; i++) { 
     tempNode = tempNode.getNext(); //go to element that before the tail 
    } 

    Node<E> tempNode2 = tail; 
    tail = tempNode; 
    tail.setNext(null); 
    size--; 
    return tempNode2.getElement(); 

    } 

    public void remove(E element){ 
    int index = 0; 
    boolean found = false; 
    Node<E> temp = head; 
    for(int i=1; i<=size; i++) {//find the node with element 
     index++; 
     if(temp.getElement().equals(element)){ 
      found = true; 
      break; 
     } 
     temp = temp.getNext(); 
    } 

    if(found){ 
     if(index == 1) 
      removeFirst(); 

     else if(index == size) 
      removeLast(); 

     else{ 
      //find the previous node 
      Node<E> prev = head; 
      for(int i=1; i<index-1; i++) { 
       prev = prev.getNext(); 
      } 

      prev.setNext(temp.getNext()); 
      temp.setNext(null); 
      size--; 
     } 
    } 
    } 

    public int searchList(E searchKey) { 
    if(size == 0) 
     return -1; 

    Node tempNode = head; 
    for(int i=1; i<=size; i++) { 
     if(tempNode.getElement().equals(searchKey)) 
      return i; //return index of the node 
     tempNode = tempNode.getNext(); 
    } 

    return -1; //not found 
    } 

    public void printList() { 
    Node tempNode = head; 
    for(int i=1; i<=size; i++) { 
     System.out.print(tempNode.getElement()); 
     if(i!=size) //if it is not last element 
      System.out.print(" - "); 
     tempNode = tempNode.getNext(); 
    } 
    System.out.println(); 

    } 

classe Persona:

public class Person 
{ 
    private String name; 
    private String surname; 
    private String address; 
    private PhoneNumber phone1; 
    private PhoneNumber phone2; 
    private PhoneNumber phone3; 

    public Person() 
    { 
     name = null; 
     surname = null; 
     address = null; 
     phone1.setPhone(0); 
     phone1.setType(""); 
     phone2.setPhone(0); 
     phone2.setType(""); 
     phone3.setPhone(0); 
     phone3.setType(""); 
    } 

    public Person(String n, String s, String a,PhoneNumber p1, PhoneNumber p2, PhoneNumber p3) 
    { 
     name = n; 
     surname = s; 
     address = a; 
     phone1 = p1; 
     phone2 = p2; 
     phone3 = p3; 

    } 

    public String getName() 
    { 
     return name; 
    } 

    public void setName(String n) 
    { 
     name = n; 
    } 
    public String getSur() 
    { 
     return surname; 
    } 

    public void setSur(String s) 
    { 
     surname = s; 
    } 

    public void insertPhone(PhoneNumber phone) 
    { 
     if(phone2 == null) 
      phone2 = phone; 
     else if(phone3 == null) 
      phone3 = phone; 
    } 

    public PhoneNumber getPhone1() 
    { 
     return phone1; 
    } 

    public PhoneNumber getPhone2() 
    { 
     return phone2; 
    } 

    public PhoneNumber getPhone3() 
    { 
     return phone3; 
    } 

    public String getAdd() 
    { 
     return address; 
    } 

    public void setAdd(String a) 
    { 
     address = a; 
    } 
+0

Si potrebbe pensare che sarebbe breve, ma in realtà dipende da cosa l'operazione di confronto dovrebbe fare se il cognome o il nome sono nulli in entrambi gli oggetti. – Powerlord

+0

Dato che è necessario scrivere il proprio codice di ordinamento e non è possibile utilizzare le funzioni di compilazione, ecco un [elenco degli algoritmi di ordinamento] (http://en.wikipedia.org/wiki/Sorting_algorithm) che si potrebbe provare e utilizzare. – nem035

risposta

2

Come tutti gli altri hanno menzionato, compareTo fa parte dell'interfaccia Comparable.

Come si implementa dipende se si desidera ordinare per cognome o nome prima e se si desidera ordinate in ordine crescente.

Ad esempio, se si desidera ordinare per cognome, in ordine crescente:

public class Person implements Comparable<Person> { 
    // the parts of Person you already have would go here 
    public int compareTo(Person person) { 
     if (person == null) { 
      return -1; 
     } 

     if (surname != null && person.getSur() == null) { 
      return -1; 
     } else if (surname == null && person.getSur() != null) { 
      return 1; 
     } else if (surname != null && person.getSur() != null) { 
      int compare = surname.compareToIgnoreCase(person.getSur()); 
      if (compare != 0) { 
       return compare; 
      } 
     } 
     // Note that we did nothing if both surnames were null or equal 

     if (name == null && person.getName() == null) { 
      return 0; 
     } else if (name != null && person.getName() == null) { 
      return -1; 
     } else if (name == null && person.getName() != null) { 
      return 1; 
     } else { 
      return name.compareToIgnoreCase(person.getName()); 
     } 
    } 
} 

(non ho fatto testare questo codice)

Questa si basa sulla realizzazione di String of compareToIgnoreCase.

Si noti che questo sposta anche tutti gli oggetti nulli e gli oggetti con nomi e cognomi null alla fine dell'elenco.

Detto questo, se si implementa Comparable, è possibile fare in modo che l'API Collections faccia il lavoro per voi usando sort.

Se si ritiene che siano necessari più metodi di ordinamento per un oggetto, è possibile creare un set di oggetti Comparator per l'ordinamento.

0

Implementare Comparable nella classe Persona.

tuo metodo compareTo() sarebbe allora qualcosa di simile:

public int compareTo(Person other) { 
    return name.compareTo(other.getName()) 
} 

Quindi utilizzare Collections.sort(<your list of Person>);

1

Potete fare la vostra classe Person implementare Comparable, e definire il seguente metodo:

public class Person implements Comparable<Person> { 

     // Your previous code 

     public int compareTo(Person other) { 
      if (other == null) { 
      // throw exception for example 
      } 
      return this.name.toLowerCase().compareTo(other.name.toLowerCase()); 
     } 
    } 
0

La firma della classe Persona dovrebbe essere come questa:

public class Person implements Comparable<Person> 

Aggiungi confrontoPer metodo alla classe Persona e utilizza Collections.sort (elenco persone) come suggerito da starf.

Problemi correlati