I have an array 'store' that stores a number of LinkedLists called intList.
How do I print the values held in each list? I tried to print it as follows:
system.out.println(store[i].toString);
but get the following in return:
intList#16ad9f5d
or something similar.
Any help would be great, thanks
A java.util.LinkedList has a nice toString() method (so no need to write it yourself, reinvent the wheel etc.), so most probably you don't call it at all. Seems like you're doing something like toArray().toString(), or maybe store.toString().
Extend LinkedList and implement toString().
Public class YourLinkedList<String> extends LinkedList<String> {
//You code goes here or blank
#Override
public String toString() {
return Arrays.toString(this.toArray());
}
}
You will get output as : [fdf, fdfdf, fdfdf]
for(List l : arr)
{
Iterator it = l.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
Something like this might work...
I think This code helps to you.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String args[])
{
LinkedList<Integer> l1=new LinkedList<Integer>();
l1.add(1);
l1.add(2);
LinkedList<Integer> l2=new LinkedList<Integer>();
l2.add(3);
l2.add(4);
LinkedList<LinkedList<Integer>> sort=new LinkedList<LinkedList<Integer>>();
sort.add(l1);
sort.add(l2);
for(List l : sort)
{
Iterator it = l.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
}
Use iterator as this :
Iterator iter = yourList.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
Related
I'm working on an assignment and I feel super close! But I just don't understand the last error message I'm getting and was wondering if you could help me understand it so I avoid it in the future.
The assignment started off with an example code:
import java.util.*;
public class Proj09{
public static void main(String args[]){
new Proj09Runner().getCollection();
}
}
class Proj09Runner{
public void getCollection(){
Collection collection = new TreeSet();
Populator.fillIt(collection);
Iterator iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}
System.out.println();
}
}
class Populator{
public static void fillIt(Collection collection){
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
}
}
Output: Able Baker aBle Charley Baker
And our job is to change that code so that it fits a different main that I'm not able to edit:
import java.util.*;
public class Proj09{
public static void main(String args[]){
Proj09Runner runner = new Proj09Runner();
Collection <String> collection = runner.getCollection();
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
Iterator <String> iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}
System.out.println();
}
}
So far, I've been playing with the Proj09Runner class:
class Proj09Runner extends Proj09{
public void getCollection(){
System.out.println("My Name.");
System.out.println();
}
}
Small change to the output, I'm supposed to add my name.
Desired output:
My Name
Able Baker aBle Charley Baker
But I keep getting different errors that go back to the line Collection <String> collection = runner.getCollection(); in the main I'm not supposed to change. I'll get called out on void's not being able to be converted to Collection <String> or "invalid method declaration; return type required."
Could y'all help me figure out why I'm getting those messages and what they mean so that I can avoid them in the future?
Thanks, I really do appreciate it.
This for sure needs improvement :
Collection <String> collection = runner.getCollection();
this does not return a Collection<String>, note your method returns nothing.
public void getCollection(){
Either your method return type and definition changes something like :
public Collection<String> getCollection(){ //followed by corresponding definition
Or you can simply use
Collection <String> collection = new HashSet() ; //whatever your collection pertain to
public Collection<String> getCollection(){
Collection collection = new TreeSet();
Populator.fillIt(collection);
Iterator iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}
System.out.println();
return collection;
}
your getCollection method is returning nothing. it should return a collection
I've been trying this and it seems to be a good direction. Keeping the main:
import java.util.*;
public class Proj09{
public static void main(String args[]){
Proj09Runner runner = new Proj09Runner();
Collection <String> collection = runner.getCollection();
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
Iterator <String> iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}
System.out.println();
}
}
I've now got:
class Proj09Runner{
public Collection<String> getCollection(){
return "Hailey";
}
}
I didn't want to reiterate what was already in the main as it seemed unnecessary. Returning the string "Hailey" addressed the old error, but a new one has popped up.
error: cannot find symbol
public Collection<String> getCollection(){
^
symbol: class Collection
location: class Proj09Runner
Do you know what that type of error indicates?
Our last unit was about inheritance, and I played with "Proj09Runner extends Proj09{" but it didn't seem to have an effect.
I wanted to go ahead and share the answer:
import java.util.*;
class Proj09Runner{
public Collection <String> getCollection(){
System.out.println("Name.");
Collection collection = new ArrayList();
return collection;
}
}
I couldn't go with TreeSet because it doesn't accept duplicates and so would only print "Baker" once, so I went with ArrayList instead.
Thanks a bunch for the feedback!
I have created a list of Strings and I need to reverse the order of them using an iterator. This is what I have but it is not working. Can someone please help me find a way to do this or tell me what I am doing wrong?
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class nameList2
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<String>();
nameList.add("Joey"); //list of Strings
nameList.add("Nicole");
nameList.add("Lucas");
nameList.add("Bobby");
nameList.add("Michelle");
nameList.add("Allie");
Iterator<String> nameIterator = nameList.iterator(); //iterator
for(String s : nameList) //for, each loop
{
if(nameIterator.hasNext()); //compile list
nameIterator.next();
}
for(String s: nameList) //for, each loop
{
if(nameIterator.hasPrevious()); //error states method cannot find hasPrevious?
System.out.println(nameIterator.previous());
}
}
}
use ListIterator instead of Iterator as :
ListIterator<String> list = nameList.listIterator(nameList.size());
// Iterate in reverse.
while(list.hasPrevious()) {
System.out.println(list.previous());
}
and you can do also as Jonk suggested using Collections.reverse(nameList);
Use two ListIterators, one at the start, one at the end and swap until they meet.
And don't forget the edge case(s)
public static void main(String[] args) {
List<String> nameList = new ArrayList<String>();
nameList.add("Joey"); //list of Strings
nameList.add("Nicole");
nameList.add("Lucas");
nameList.add("Bobby");
nameList.add("Michelle");
nameList.add("Allie");
ListIterator<String> list = nameList.listIterator();
System.out.println("Before Reversed\n");
while(list.hasNext()){
System.out.println(list.next());
}
System.out.println("\nAfter Reversed \n");
while(list.hasPrevious()){
System.out.println(list.previous());
}
}
This question already has answers here:
Java Beginner: How do I link one linked list to another?
(6 answers)
Closed 8 years ago.
I hava list of LinkedList and I want to make (unable to modified) One connected LinkedList .
and not change the original linkedLists.
LinkedLists<String> a=new LinkedList<String>();
LinkedLists<String> b=new LinkedList<String>();
LinkedLists<String> c=new LinkedList<String>();
a.add("as");
a.add("sa");
a.add("bb");
b.add("as");
b.add("sa");
c.add("bb");
c.add("d");
c.add("ya");
the new LinkedList contain ya d bb sa as bb sa as
so I want to make one Linked List.I preffer Not copy the items casue this consume memory.
Only connect theme for go all over the items not to modified the items.
Thanks!
Try Collections#unmodifiableList()
Sample code:
LinkedList<String> a = new LinkedList<String>();
a.add("as");
a.add("sa");
a.add("bb");
a.add("as");
a.add("sa");
a.add("bb");
a.add("d");
a.add("ya");
List<String> b = Collections.unmodifiableList(a.subList(0, 3));
List<String> c = Collections.unmodifiableList(a.subList(5, 8));
b.set(0, "aa"); // not allowed
c.add("zz"); // not allowed
a.set(6, "zz"); // allowed and List c is also updated.
Try subclassing List. Here's a quick example I put together below. It's largely incomplete but you'll get the idea.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Experiment {
public static void main(String[] args) throws Exception {
LinkedList<String> a = new LinkedList<String>();
LinkedList<String> b = new LinkedList<String>();
LinkedList<String> c = new LinkedList<String>();
a.add("as");
a.add("sa");
a.add("bb");
b.add("as");
b.add("sa");
c.add("bb");
c.add("d");
c.add("ya");
MyLinkedList<String> list = new MyLinkedList<String>();
list.add(a);
list.add(b);
list.add(c);
for (String s : list) {
System.out.println(s);
}
}
private static class MyLinkedList<T> extends LinkedList<T> {
private List<List<T>> lists = new LinkedList<List<T>>();
public void add(LinkedList<T> list) {
lists.add(list);
}
#Override
public Iterator<T> iterator() {
return new MyLinkedIterator<T>(lists);
}
}
private static class MyLinkedIterator<T> implements Iterator<T> {
private List<List<T>> lists;
private int listIndex = 0;
private int currentIndex = 0;
private T next;
public MyLinkedIterator(List<List<T>> lists) {
this.lists = lists;
}
public boolean hasNext() {
if (listIndex >= lists.size()) return false;
List<T> list = lists.get(listIndex);
if (currentIndex >= list.size()) {
currentIndex = 0;
listIndex++;
return hasNext();
}
next = list.get(currentIndex++);
return true;
}
public T next() {
return next;
}
public void remove() {
}
}
}
How about this:
LinkedList<String> a=new LinkedList<String>();
LinkedList<String> b=new LinkedList<String>();
LinkedList<String> c=new LinkedList<String>();
a.add("as");
a.add("sa");
a.add("bb");
b.add("as");
b.add("sa");
c.add("bb");
c.add("d");
c.add("ya");
LinkedList<String> unionList = new LinkedList<String>();
unionList.addAll(a);
unionList.addAll(b);
unionList.addAll(c);
LinkedList<String> unmodifiableUnion = Collections.unmodifiableList(unionList);
It uses addAll() to add all lists into a new one and returns an unmodifiable list from it using Collections.unmodifiableList()
Update
If memory consumption is your problem, the standard JDK is not enough. You will have to implement your own or use an existing one.
To implement your own you can usa a LinkedList<List<T>> to store your linked lists and implement the List interface. mprivat started an implementation for you.
To use an existing one, you could use:
Trove: it is considered really good and fast if no fastest with least memory consumption, at least that is what I have observed in my usages of it.
this implementation: it is a singly linked list so it consumes less memory and has a merge method that will merge 2 linked lists using their "pointers" as you would expect.
I have the following code sample, im pretty sure the first block should be placed in the main(), but where do I place the second block to make this Iterator example work?
List<String> myList= new ArrayList<String> ( );
Where do i place this? Would I need to create a second class?
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
}
then there's this typical iterator pattern....is this in any way related to the second code block?
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
Object temp;
while( it.hasNext() )
{
temp = it.next();
System.out.println( temp );
}
return;
}
It isn't clear what you want to achieve, if you are asking how to pass your ArrayList (local variable in main) to the printAll method, do something like below:
public class XYZ {
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
Object temp;
while(it.hasNext() )
{
temp = it.next();
System.out.println( temp );
}
return;
}
public static void main(String...args){
List<String> myList= new ArrayList<String> ( );
myList.add("Hello");
myList.add("World");
printAll(myList);//passing myList to printAll
}
}
Is there a reason you're trying to use an interator?
You can do something like this, assuming you're on Java 5.
List<String> myList= new ArrayList<String> ( );
// set up list... etc.
for(String currentString : myList) {
System.out.println(currentString);
}
Iterators are only useful if you need to remove some element of the collection while traversing it (using the Iterator.remove() method). Otherwise, just use a for-each loop.
I am having trouble using Iterator in java.
it=myHash.iterator();
while (it.hasNext())
if (it.next() satisfying something)
do something
while (it.hasNext())
if (it.next() satisfying something)
it.remove();
I am trying to iterate hashset twice, and the first loop making it.hasNext() return false. How to i resolve this?
I tried even adding the edit as you guys suggested, still not working...
You're reusing the same iterator - and that's been invalidated by adding new items to the set.
You should call iterator() again on the set:
it = set.iterator();
You can't reset the existing iterator
EDIT: Here's some sample code which shows this working:
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("food");
set.add("bad");
set.add("hungry");
set.add("neighbour");
Iterator<String> it = set.iterator();
// Remove any string longer than 4
while (it.hasNext())
{
if (it.next().length() > 4)
{
it.remove();
}
}
set.add("new long text");
set.add("x");
// Remove any string shorter than 4
it = set.iterator();
while (it.hasNext())
{
if (it.next().length() < 4)
{
it.remove();
}
}
// Dump the results
for (String x : set)
{
System.out.println(x);
}
}
}
This gives the results "new long text" and "food".
Ideally, what you are looking for is a reset operation on an Iterator. Iterators are meant to be unidirectional and one-time use, as such they don't have support for reset in Java.
You can either get hold of a new Iterator instance or use ListIterator interface which allows you to look backwards using previous().
Edit:
You are using remove() on the iterator which is also removing elements from the original set. In such a case you should consider making a copy of the set since you want to iterate over the elements all over again:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
public class IteratorSnippet {
public static void main(String[] args) {
final HashSet<Integer> myHash = new HashSet<Integer>();
myHash.addAll(Arrays.asList(1, 2, 3, 4, 5));
// make copy before using iterator with remove
final HashSet<Integer> myHash2 = new HashSet<Integer>(myHash);
Iterator<Integer> it = myHash.iterator();
System.out.println("First go...");
while (it.hasNext()) {
System.out.println(it.next());
it.remove();
}
it = myHash2.iterator();
System.out.println("Second go...");
while (it.hasNext()) {
System.out.println(it.next());
}
}
}