Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [JAVA] Linkedlist e metodo toArray()

    Devo comparare due code di tipo LinkedList. Il modo più semplice che mi è venuto in mente è

    codice:
    if(lst.toArray().equals(lst2.toArray()))
        return true;
    else
        return false;
    Il fatto è che dà sempre e comunque false.....Qualcuno sa come mai, o mi sa dire un altro metodo facile per confrontare due linkedlist (mi interessa solamente l'uguaglianza)? Grazie!

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: [JAVA] Linkedlist e metodo toArray()

    Originariamente inviato da Lasentinella
    Devo comparare due code di tipo LinkedList. Il modo più semplice che mi è venuto in mente è

    codice:
    if(lst.toArray().equals(lst2.toArray()))
        return true;
    else
        return false;
    Il fatto è che dà sempre e comunque false.....
    Certo che dà false! Gli array sono degli oggetti in quanto estendono Object. Ma per gli array non viene ridefinito equals(), rimane quello implementato in Object che si basa solo sulla uguaglianza dei reference.
    E i due array ottenuti con toArray() sono certamente oggetti diversi, quindi con reference diversi.

    AbstractList (una superclasse di LinkedList) invece ridefinisce equals():

    Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order.
    Quindi molto semplicemente:

    if (lst.equals (lst2))
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Ahhhhhhhh hai ragione!!!!!!!!!!!!!!!!!!!!!!!

    Grazie mille, mi sei stato molto d'aiuto


Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.