Archief - Java, probleem met inlezen uit een bestand

Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.

Gonnor

Legacy Member
Hallo

Ik heb een klein programmatje gemaakt om 2 collecties van films in te lezen en die te vergelijken met elkaar en de gemeenschappelijke films eruit te halen. Maar het werkt niet.

Code:
    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(new File("collectie1.txt"));
            ArrayList<String> filmCollectie = new ArrayList<String>();
            while (sc.hasNextLine()) {
                String film = sc.nextLine().trim();
                System.out.println(film);
                filmCollectie.add(film);
            }
            sc.close();
            Scanner sc2 = new Scanner(new File("collectie2.txt"));
            System.out.println("test");
            while (sc2.hasNextLine()){
                String film = sc2.nextLine().trim();
                System.out.println(film);
                if (filmCollectie.contains(film)){
                    System.out.println(film);
                }
            }
            sc2.close();
        } catch (FileNotFoundException ex) {
            System.out.println("Collecties niet gevonden.");
        }
    }

De eerste lus wil niet alles inlezen en de tweede lus wil zelf niet beginnen met inlezen. De system.out.prints in de while lussen zijn ervoor te testen. Kan iemand me helpen de fout eruit te halen?

Dit zijn de 2 collecties:
Code:
1984 [1956]
25th Hour [2002]
L.A. Confidential [1997]
3:10 to Yuma [2007]
A Beautiful Mind [2001]
A Clockwork Orange [1971]
A Place in the Sun [1951]
A River Runs Through It [1992]
A Time to Kill [1996]
A Walk to Remember [2002]
About a Boy [2002]
About Schmidt [2002]
Alice in Wonderland [2010]
American Psycho [2000]
Angels & Demons [2009]
Apocalypse Now [1979]
Apollo 13 [1995]
Atonement [2007]
Babe [1995]
Blade Runner [1982]
Born on the Fourth of July [1989]
Breakfast at Tiffany's [1961]
Cape Fear [1991]
Capote [2005]
Carlito's Way [1993]
Carrie [1976]
Casino [1995]
Charlotte's Web [1973]
Children of Men [2006]
Congo [1995]
Coraline [2009]
Cujo [1983]
Dances with Wolves [1990]
Dangerous Minds [1995]
Die Hard [1988]
Diggstown AKA Midnight Sting [1992]
Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb [1964]
Dracula [1931]
Eat Pray Love [2010]
Emma [1996]
Fahrenheit 451 [1966]
Fast Times at Ridgemont High [1982]
Field of Dreams [1989]
Fight Club [1999]
Flickan som lekte med elden AKA The Girl Who Played with Fire [2009]
Forrest Gump [1994]
Frankenstein [1931]
Friday Night Lights [2004]
Fried Green Tomatoes [1991]
Full Metal Jacket [1987]
Gettysburg [1993]
Girl, Interrupted [1999]
Gone Baby Gone [2007]
Gone with the Wind [1939]
Goodfellas [1990]
Harry Potter and the Chamber of Secrets [2002]
Harry Potter and the Deathly Hallows: Part 1 [2010]
Harry Potter and the Deathly Hallows: Part 2 [2011]
Harry Potter and the Goblet of Fire [2005]
Harry Potter and the Half-Blood Prince [2009]
Harry Potter and the Order of the Phoenix [2007]
Harry Potter and the Prisoner of Azkaban [2004]
Harry Potter and the Sorcerer's Stone AKA Harry Potter and the Philosopher's Stone [2001]
Holes [2003]
How Stella Got Her Groove Back [1998]
Hugo [2011]
In the Name of the Father [1993]
Instinct [1999]
Interview with the Vampire: The Vampire Chronicles [1994]
Jaws [1975]
Jurassic Park [1993]
Kings Row [1942]
Kiss Kiss Bang Bang [2005]
Kiss of Death [1947]
Lady in the Lake [1947]
Legends of the Fall [1994]
Les Misérables [1998]
Limitless [2011]
Little Women [1994]
Lonelyhearts [1958]
Lord of the Flies [1963]
Luftslottet som sprängdes AKA The Girl Who Kicked the Hornet's Nest [2009]
Män som hatar kvinnor AKA The Girl with the Dragon Tattoo [2009]
Man Hunt [1941]
MASH [1970]
Memoirs of a Geisha [2005]
Mercury Rising [1998]
Message in a Bottle [1999]
Midnight Cowboy [1969]
Million Dollar Baby [2004]
Minority Report [2002]
Misery [1990]
Munich [2005]
My Sister's Keeper [2009]
Mystic River [2003]
Never Let Me Go [2010]
No Country for Old Men [2007]
Of Mice and Men [1992]
Once Upon a Time in America [1984]
One Flew Over the Cuckoo's Nest [1975]
Ordinary People [1980]
Patriot Games [1992]
Percy Jackson & the Olympians: The Lightning Thief [2010]
Planet of the Apes [1968]
Pride & Prejudice [2005]
Primary Colors [1998]
Psycho [1960]
Rebecca [1940]
Romancing the Stone [1984]
Roots [1977]
Rosemary's Baby [1968]
Running with Scissors [2006]
Scarface [1983]
Schindler's List [1993]
Sense and Sensibility [1995]
Shadowlands [1993]
Shooter [2007]
Shutter Island [2010]
Sideways [2004]
Sophie's Choice [1982]
Sphere [1998]
Stand by Me [1986]
Stardust [2007]
Terms of Endearment [1983]
The Adjustment Bureau [2011]
The Adventures of Huckleberry Finn [1960]
The Assassination of Jesse James by the Coward Robert Ford [2007]
The Bourne Identity [2002]
The Bourne Supremacy [2004]
The Bourne Ultimatum [2007]
The Bridge on the River Kwai [1957]
The Call of the Wild [1935]
The Chronicles of Narnia: Prince Caspian [2008]
The Chronicles of Narnia: The Lion, the Witch and the Wardrobe [2005]
The Chronicles of Narnia: The Voyage of the Dawn Treader [2010]
The Client [1994]
The Color of Money [1986]
The Color Purple [1985]
The Crucible [1996]
The Curious Case of Benjamin Button [2008]
The Da Vinci Code [2006]
The English Patient [1996]
The Exorcist [1973]
The Firm [1993]
The First Wives Club [1996]
The Fly [1986]
The Fox and the Hound [1981]
The Godfather [1972]
The Golden Compass [2007]
The Graduate [1967]
The Grapes of Wrath [1940]
The Great Escape [1963]
The Great Gatsby [1974]
The Green Mile [1999]
The Help [2011]
The Hobbit [1977]
The Hunt for Red October [1990]
The Hustler [1961]
The Killing Fields [1984]
The King and I [1956]
The King's Speech [2010]
The Last of the Mohicans [1992]
The Lord of the Rings: The Fellowship of the Ring [2001]
The Lord of the Rings: The Return of the King [2003]
The Lord of the Rings: The Two Towers [2002]
The Lovely Bones [2009]
The Magician [1926]
The Mambo Kings [1992]
The Man in the Iron Mask [1998]
The Manchurian Candidate [1962]
The Natural [1984]
The Notebook [2004]
The Old Man and the Sea [1999]
The Pelican Brief [1993]
The Prince of Tides [1991]
The Princess Bride [1987]
The Road [2009]
The Secret Garden [1993]
The Secret Life of Bees [2008]
The Secret of NIMH [1982]
The Shawshank Redemption [1994]
The Silence of the Lambs [1991]
The Thing [1982]
The Thing from Another World [1951]
The Time Traveler's Wife [2009]
The Twilight Saga: Breaking Dawn - Part 1 [2011]
The Twilight Saga: Eclipse [2010]
The Twilight Saga: New Moon [2009]
Timeline [2003]
To Kill a Mockingbird [1962]
Total Recall [1990]
Trainspotting [1996]
True Grit [2010]
Tuck Everlasting [2002]
Tuesdays with Morrie [1999]
Twilight [2008]
Under Siege [1992]
War of the Worlds [2005]
Water for Elephants [2011]
Wuthering Heights [1939]
The Informers [2009]
The Hunger Games [2012]
Less Than Zero [1987]
Jackie Brown [1997]
Choke [2008]
The Girl with the Dragon Tattoo [2011]
Christine [1983]
Primal Fear [1996]
1408 [2007]
Thinner [1996]
The Dead Zone [1983]
Pet Sematary [1989]
The Beach [2000]
São Bernardo [1972]
Seven Years in Tibet [1997]
The Spy Who Came in from the Cold [1965]
Perfume: The Story of a Murderer [2006]
Cosmopolis [2012]
All Quiet on the Western Front [1930]
Abraham Lincoln: Vampire Hunter [2012]
Die Hard 2 [1990]
The Tesseract [2003]
Bright Lights, Big City [1988]
Catch-22 [1970]
Angela's Ashes [1999]
The Wizard of Oz [1939]
Dolores Claiborne [1995]
The Sheltering Sky [1990]
Beloved [1998]
Presumed Innocent [1990]
Hawaii [1966]
The Sun Also Rises [1957]
Long Day's Journey Into Night [1962]
The Visual Bible: The Gospel of John [2003]
Little Women [1949]
Anne of Green Gables [1985]
Dracula AKA Bram Stoker's Dracula [1992]
Charlie Wilson's War [2007]
In Cold Blood [1967]
John Dies at the End [2012]
The Perks of Being a Wallflower [2012]
Jesus' Son [1999]
Snabba cash AKA Easy Money [2010]
Hypnotisören AKA The Hypnotist [2012]
The Hobbit: An Unexpected Journey [2012]
Sworn to Silence AKA An Amish Murder [2013]
Fat Kid Rules the World [2012]
Silver Linings Playbook [2012]
Killing Them Softly [2012]
The American [2010]
Jack Reacher [2012]
Lord of the Flies [1990]
Morfiy AKA Morphine [2008]
The Joy Luck Club [1993]
The Shining [1980]
Wag the Dog [1997]
Bridget Jones's Diary [2001]
The Accidental Tourist [1988]
Quiz Show [1994]
Out of Sight [1998]
First Blood [1982]
Kiss of the Spider Woman [1985]
Willy Wonka & the Chocolate Factory [1971]
The Year of Living Dangerously [1982]
2001: A Space Odyssey [1968]
Master and Commander: The Far Side of the World [2003]
Memento [2000]
Das Boot AKA The Boat [1981]
Raging Bull [1980]
The Postman Always Rings Twice [1981]
The Untouchables [1987]
Casino Royale [2006]
The Sum of All Fears [2002]
Clear and Present Danger [1994]
The Scarlet Letter [1926]
The Scarlet Letter [1995]
Bringing Out the Dead [1999]
A Simple Plan [1998]
The Pact [2002]
Get Shorty [1995]
Be Cool [2005]
Thief [1981]
The Sweet Hereafter [1997]
Prozac Nation [2001]
It's Kind of a Funny Story [2010]
Eragon [2006]
Cloud Atlas [2012]
The Fountainhead [1949]
Atlas Shrugged: Part I [2011]
Atlas Shrugged II: The Strike [2012]
Argo [2012]
Lincoln [2012]
Life of Pi [2012]
Tinker Tailor Soldier Spy [2011]
Moneyball [2011]
The Descendants [2011]
Winter's Bone [2010]
127 Hours [2010]
The Social Network [2010]
Up in the Air [2009]
An Education [2009]
Precious: Based on the Novel Push by Sapphire [2009]
The Reader [2008]
Slumdog Millionaire [2008]
Le scaphandre et le papillon AKA The Diving Bell and the Butterfly [2007]
There Will Be Blood [2007]
Little Children [2006]
The Constant Gardener [2005]
Diarios de motocicleta AKA The Motorcycle Diaries [2004]
Seabiscuit [2003]
Cidade de Deus AKA City of God [2002]
The Hours [2002]
Adaptation. [2002]
The Pianist [2002]
Wonder Boys [2000]
Wo hu cang long AKA Crouching Tiger, Hidden Dragon [2000]
Chocolat [2000]
The Hitchhiker's Guide to the Galaxy [2005]
More Than Murder [1984]
The Prestige [2006]
Nineteen Eighty-Four AKA 1984 [1984]
Warm Bodies [2013]
Crime and Punishment [1935]
Crime et châtiment AKA Crime and Punishment [1956]
To Die For [1995]
Paranoid Park [2007]
Mannen som elsket Yngve AKA The Man Who Loved Yngve [2008]
Simon och ekarna AKA Simon and the Oaks [2011]
Der Baader Meinhof Komplex AKA The Baader Meinhof Complex [2008]
Going Postal [2010]
The Great Gatsby [2013]
The Outsiders [1983]
Låt den rätte komma in AKA Let the Right One In [2008]
Let Me In [2010]
A Single Shot [2013]
Odd Thomas [2013]
Imaginary Crimes [1994]
The Dreamers [2003]
John Carter [2012]
Night Train to Lisbon [2013]
The General's Daughter [1999]
8-Pallo AKA 8-Ball [2013]
The Ice Storm [1997]
What Maisie Knew [2012]
The Reluctant Fundamentalist [2012]
On the Beach [1959]
On the Beach [2000]
Syrup [2013]
Animal Factory [2000]
Mean Girls [2004]
Cruel Intentions [1999]
Freaky Deaky [2012]
Eyes Wide Shut [1999]
Clueless [1995]
Ed Wood [1994]
Nanny McPhee [2005]
October Sky [1999]
It's a Wonderful Life [1946]
A Scanner Darkly [2006]
Stalker [1979]
Solaris [2002]
Solyaris AKA Solaris [1972]
James and the Giant Peach [1996]
Animal Farm [1954]
Animal Farm [1999]
Starting Out in the Evening [2007]
Something Borrowed [2011]
The Sisterhood of the Traveling Pants [2005]
The Sisterhood of the Traveling Pants 2 [2008]
Angus, Thongs and Perfect Snogging [2008]
Killing Kennedy [2013]
Salem's Lot [1979]
Stir of Echoes [1999]

Code:
Hon dansade en sommar AKA One Summer of Happiness [1951]
Le salaire de la peur AKA The Wages of Fear [1953]
Hobson's Choice [1954]
Die Ratten [1955]
Invitation to the Dance [1956]
12 Angry Men [1957]
Smultronstället AKA Wild Strawberries [1957]
Les cousins AKA The Cousins [1959]
El lazarillo de Tormes [1959]
La Notte AKA The Night [1961]
A Kind Of Loving [1962]
Il diavolo [1963]
Bushidô zankoku monogatari AKA Cruel Tales Of Bushido [1963]
Susuz yaz [1964]
Alphaville, une étrange aventure de Lemmy Caution AKA Alphaville, A Strange Adventure of Lemmy Caution [1965]
Cul-de-sac [1966]
Le départ AKA The Departure [1967]
Ole dole doff AKA Eeny Meeny Miny Moe AKA Who Saw Him Die? [1968]
Rani radovi [1969]
Il Giardino dei Finzi-Contini AKA The Garden of the Finzi-Continis [1970]
I racconti di Canterbury AKA The Canterbury Tales [1972]
Ashani Sanket AKA Distant Thunder [1973]
The Apprenticeship of Duddy Kravitz [1974]
Örökbefogadás AKA Adoption [1975]
Buffalo Bill and the Indians AKA Sitting Bull's History Lesson [1976]
Voskhozhdeniye AKA The Ascent [1977]
Las truchas [1978]
Ascensor [1978]
Las palabras de Max [1978]
David [1979]
Heartland [1979]
Palermo oder Wolfsburg [1980]
Deprisa, deprisa AKA Faster, Faster [1981]
Die Sehnsucht der Veronika Voss AKA Veronika Voss [1982]
Ascendancy [1983]
La colmena AKA The Beehive [1982]
Love Streams [1984]
Die Frau und der Fremde [1985]
Wetherby [1985]
Stammheim - Die Baader-Meinhof-Gruppe vor Gericht AKA Stammheim: The Trial of the Baader-Meinhof Group [1986]
Tema [1979]
Hong gao liang AKA Red Sorghum [1987]
Rain Man [1988]
Music Box [1989]
Skrivánci na niti AKA Larks on a String [1990]
La casa del sorriso AKA The House of Smiles [1991]
Grand Canyon [1991]
Xian hun nu AKA Woman Sesame Oil Maker [1993]
Xi yan AKA The Wedding Banquet [1993]
In the Name of the Father [1993]
L'appât AKA The Bait [1995]
Sense and Sensibility [1995]
The People vs. Larry Flynt [1996]
Central do Brasil AKA Central Station [1998]
The Thin Red Line [1998]
Magnolia [1999]
Intimacy [2001]
Sen to Chihiro no kamikakushi AKA Spirited Away [2001]
Bloody Sunday [2002]
In This World [2002]
Gegen die Wand AKA Head-On [2004]
U-Carmen eKhayelitsha [2005]
Grbavica AKA Grbavica: The Land of My Dreams [2006]
Tuya de hun shi AKA Tuya's Marriage [2006]
Tropa de Elite AKA Elite Squad [2007]
La teta asustada AKA The Milk of Sorrow [2009]
Bal AKA Honey [2010]
Jodaeiye Nader az Simin AKA A Separation [2011]
Cesare deve morire AKA Caesar Must Die [2012]
Pozitia copilului AKA Child's Pose [2013]

In the Name of the Father [1993] is de gemeenschappelijke film.

Bedankt.

NoGo

Legacy Member
Beetje vaag wat je probleem is, bij mij krijg ik als output

In the Name of the Father [1993]
Sense and Sensibility [1995]

Ziet er correct uit? Worden de bestanden wel goed ingelezen? Waar staan ze en welke formaat hebben ze?

profound

Legacy Member
Ik zie ook niet direct een probleem, kijk eens in je text files of er geen onregelmatigheden zijn bij de formatting

Gonnor

Legacy Member
NoGo zei:
Beetje vaag wat je probleem is, bij mij krijg ik als output

In the Name of the Father [1993]
Sense and Sensibility [1995]

Ziet er correct uit? Worden de bestanden wel goed ingelezen? Waar staan ze en welke formaat hebben ze?

Bedankt om te antwoorden.

Ik wou zelf ook dat het minder vaag is, raar dat jij wel een juiste output krijgt. De bestanden staan in mijn project map en zijn .txt formaat. Ik krijg geen FileNotFound exceptie als ik het programma laat lopen.
De laatste 3 output strings van de eerste lus zijn deze:

Kings Row [1942]
Kiss Kiss Bang Bang [2005]
Kiss

Daarna schrijft hij "test" uit en daarna BUILD SUCCESSFUL (total time: 0 seconds), dus aan de 2de lus begint hij niet.
Ik zal een keer de 2 txt files opnieuw maken.

@profound, op het eerste zicht zie ik geen onregelmatigheden. Ik gebruik daarom ook .trim() om eventuele overtollige spaties weg te laten

EDIT: werkt nog altijd niet.
sc.hasNextLine() == false achter de film Kiss (die normaal Kiss of Death [1947] noemt)
sc2.hasNextLine() == false vanaf het begin, dus hij gaat nooit in de while lus.

Als ik de collectie2 in de eerste while lus zet en collectie1 in de tweede werkt het nog altijd niet. Zelfde probleem. Maar dan omgekeerd (while lus 1 werkt niet, while lus 2 stopt na Kiss (Kiss of Death [1947])

YaMo

Legacy Member
Ik zou zeggen: delete die files, en copy paste de tekst uit die spoilers in je eerste post naar 2 nieuwe files.
Waarschijnlijk is er ergens een of ander vaag character in die ene file geslopen waar Scanner niet tegen kan.

NoGo

Legacy Member
Krijg hetzelfde effect als ik als encoding type UTF-8 of Unicode kies bijvoorbeeld. Zou het misschien ook kunnen dat hij een van deze default pakt? Ben niet echt zo thuis daar in :p

Met Scanner sc = new Scanner(new File("collectie1.txt"), "windows-1252"); gaat het dan weer wel :p (schijnbaar mijn standaard)

Gonnor

Legacy Member
YaMo zei:
Ik zou zeggen: delete die files, en copy paste de tekst uit die spoilers in je eerste post naar 2 nieuwe files.
Waarschijnlijk is er ergens een of ander vaag character in die ene file geslopen waar Scanner niet tegen kan.

Getest, nog altijd hetzelfde probleem.
Ik sla de txt bestanden wel op als ANSI codering met kladblok, mss ligt het daaraan?

YaMo

Legacy Member
NoGo zei:
Krijg hetzelfde effect als ik als encoding type UTF-8 of Unicode kies bijvoorbeeld. Zou het misschien ook kunnen dat hij een van deze default pakt? Ben niet echt zo thuis daar in :p

Met Scanner sc = new Scanner(new File("collectie1.txt"), "windows-1252"); gaat het dan weer wel :p (schijnbaar mijn standaard)

Hmm, bij mij is de default charset blijkbaar UTF-8 en het werkt zonder probleem.
Ook als ik het expliciet op UTF-8 zet.
Ik werk wel in linux...

Gonnor

Legacy Member
Ik heb de codering bij het opslaan van de collecties veranderd van ANSI naar UTF-8 en het werkt nu zonder problemen. Hoe kan ik zorgen dat de scanner ANSI codering ook kan lezen?

NoGo

Legacy Member
Gonnor zei:
Ik heb de codering bij het opslaan van de collecties veranderd van ANSI naar UTF-8 en het werkt nu zonder problemen. Hoe kan ik zorgen dat de scanner ANSI codering ook kan lezen?

Encoding type meegeven, voor u waarschijnlijk dus Scanner sc = new Scanner(new File("collectie1.txt"), "windows-1252");, ANSI is geen bepaalde encoding op zich.

Gonnor

Legacy Member
iterums zei:
Btw, een HashSet<String> is waarschijnlijk een betere datastructuur voor je doeleinden. Nu onderzoek je voor elke item in je tweede bestand in het slechtste geval alle items in het eerste bestand. Zie bijvoorbeeld https://stackoverflow.com/questions/10196343/hash-set-and-array-list-performances

Thanks, ik heb eind dit semester maar pas een hash-set gezien en was ervoor altijd gewend met een arraylist te werken. Daarom dat ik niet onmiddellijk dacht aan een hash-set. Ik zal het aanpassen.

YaMo

Legacy Member
Gonnor zei:
Thanks, ik heb eind dit semester maar pas een hash-set gezien en was ervoor altijd gewend met een arraylist te werken. Daarom dat ik niet onmiddellijk dacht aan een hash-set. Ik zal het aanpassen.

Bij de meeste collecties staat in de documentatie de tijdscomplexiteit voor een aantal operaties. Je kan die gebruiken (samen met andere vereiste eigenschappen) om de meest geschikte collectie te kiezen.

Gonnor

Legacy Member
YaMo zei:
Bij de meeste collecties staat in de documentatie de tijdscomplexiteit voor een aantal operaties. Je kan die gebruiken (samen met andere vereiste eigenschappen) om de meest geschikte collectie te kiezen.

Kun je eens de site geven waarvan jij je documentatie haalt geven? Ik haal mijn informatie bij java docs 7 en ik zie de tijdcomplexiteit daar niet tussen staan. Ofwel kijk ik er gewoon over.

EDIT: @iterums
Is een TreeSet dan niet nog beter dan een HashSet? Een TreeSet is geordend, maakt dat dan niet het zoeken gemakkelijker (tijdscomplexiteitsgewijs)?

YaMo

Legacy Member
Gonnor zei:
Kun je eens de site geven waarvan jij je documentatie haalt geven? Ik haal mijn informatie bij java docs 7 en ik zie de tijdcomplexiteit daar niet tussen staan. Ofwel kijk ik er gewoon over.

EDIT: @iterums
Is een TreeSet dan niet nog beter dan een HashSet? Een TreeSet is geordend, maakt dat dan niet het zoeken gemakkelijker (tijdscomplexiteitsgewijs)?

HashSet (Java Platform SE 7 )
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

ArrayList (Java Platform SE 7 )
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

TreeSet (Java Platform SE 7 )
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Dus voor lange lijsten zal een HashSet allicht sneller zijn dan een TreeSet.
Let ook wel op dat sommige collecties nog bepaalde vereisten kunnen stellen voor object die je er in wilt steken (hashCode() en equals() correct geïmplementeerd, Comparable interface geïmplementeerd, ...)

iterums

Legacy Member
Gonnor zei:
Kun je eens de site geven waarvan jij je documentatie haalt geven? Ik haal mijn informatie bij java docs 7 en ik zie de tijdcomplexiteit daar niet tussen staan. Ofwel kijk ik er gewoon over.

EDIT: @iterums
Is een TreeSet dan niet nog beter dan een HashSet? Een TreeSet is geordend, maakt dat dan niet het zoeken gemakkelijker (tijdscomplexiteitsgewijs)?
Waarschijnlijk niet (zie de documentatie gegeven door YaMo, verwachte tijdscomplexiteit van O(1) versus O(log n)), maar het beste wat je kunt doen is altijd zelf eens te benchmarken op jouw eigen, representatieve data.

Simpelweg gezegd is een HashSet geschikt als je enkel geïnteresseerd bent of een element aanwezig is, en niet in enige volgorde (zoals toegevoegd of een andere sortering).
Zie bijvoorbeeld ook https://stackoverflow.com/questions/1463284/hashset-vs-treeset

Gonnor

Legacy Member
Bedankt beiden voor jullie antwoord, raar dat ik dat niet ben tegengekomen op de java docs.

Als ik eens wat meer tijd heb, zal ik zeker eens benchmarken om het verschil te zien.

MilM

Legacy Member
Indien je dit programma echt wilt gaan gebruiken, converteer je de strings best naar bijvoorbeeld LowerCase.
(je kan eventueel meerdere spaces ook verwijderen ipv enkel een trim uit te voeren)
Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.
Terug
Bovenaan