Using Iterator To Add To Arraylist

Nov 12, 2014

I am trying to add the contents of the iterator to an arraylist so I can do other stuff to it, however I am getting an error when I actually try adding it to the list, stating that

"The method add(Map.Entry<String,myObject>) in the type ArrayList<Map.Entry<String,myObject>> is not applicable for the arguments (myObject)"

Here is what I have tried doing:

Iterator<Map.Entry<String, myObject>> iterator = hash.entrySet().iterator();//hash is my HashMap object
ArrayList<Map.Entry<String, myObject>> list = new ArrayList<Map.Entry<String, myObject>>();
while(iterator.hasNext()){
Map.Entry<String, myObject> entry = iterator.next();
list.add(entry.getValue());//error here
}

View Replies


ADVERTISEMENT

Iterator Next Not Working In If

Apr 4, 2014

I need to find out if one array list is a sub-sequence of another. The elements in the first list all need to be in the second list and must be in the same order. So s1<n, t, a> is a sub-sequence of s2<q, n, f, r, t, d, a>, but s1<a, a, t> is not a sub-sequence of s2<a, t, a>. I need to use iterators to go through each list, and I should only go through each list once (since it has to be in the same order) so nested loops don't seem like they would work because it would start at the beginning of one list every time it moved to another element in the outer loop's list.I seem to have an issue where the itr1. next()
is ignored when in an if statement.

My current code just stalls and will never stop running. I've also switched things around and put the not equal check after the if it is equal and it throws a NoSuchElementException.

import dataStructures.*;
public class Subsequence3
{
public static void main(String[] args)
{
ArrayList<Character> s1 = new ArrayList<Character>();
s1.add('n');
s1.add('p');
s1.add('a');

[code]....

View Replies View Related

How To Use Iterator Instead Of Foreach Loop

Mar 25, 2015

I am trying to use an iterator instead of a foreach loop to go through a list of inventories to see if a car is rearDrive and count how many are rearDrive but somehow I seem to be missing something that the counter isn't working as expected.

public int howManyAreRearWheelDrive(){
int i = 0;
int counter = 0;
int inventSize = inventory.size()-1;
while(i < inventSize){
boolean wheelDrive = inventory.get(i).getIsRearWheelDrive();
if( wheelDrive == true){
counter++;
}
}
return counter; // returning here doesn't give me anything
}

View Replies View Related

Why Iterator Should Be Inner Class In Collections

Feb 24, 2014

The Iteratior provides the functionality of traversing and removal which we can achieve through normal for loop and remove() of the data structure.Then, why do we need Iterator explicitly and as an inner class?

View Replies View Related

Cannot Return Object Of Iterator As Its An Interface

Mar 3, 2014

What does the iterator() method return???it can't return an object of Iterator as it's an interface...

View Replies View Related

Creating Custom Fail-fast Iterator?

Feb 8, 2015

As part of a homework assignment in my 1st Java Class, I am creating my own Circular Generic LinkedList and Array class. My class uses the Queue Interface Extends Iterable but I am creating my own methods to work with. For the most part, I believe I have been successful in creating the class aside from one method. That method is the Iterator<E> iterator().

/**
* Return a fail-fast iterator, which throw a java.util.ConcurrentModificationException
* if the client modifies the collection (via enqueue(...) or dequeue()) during iteration.
*/
@Override
public Iterator<E> iterator() {

I don't understand how an iterator, let alone a "fail-fast" iterator ties into my project. I've spent hours reading up on a way to imploy my own generic fail-fast iterator but to no avail.

I feel like I could come up with some workable code if I knew what the point is to useing a user-defined, non Java Library iterator is to do.

As well, does throwing a ConcurrentModificationException require a try and catch block?

View Replies View Related

Linked List Iterator Remove Implementation

May 3, 2014

I have a problem with a linked list iterator, my problem is implementing the iterator.remove method given the following code:

package mapsql.util;
import java.util.Iterator;
public class LinkedList<T> implements List<T> {
private class Node implements Position<T> {
T element;
Node next, prev;
public Node(T element) {
this.element = element;

[Code] ....

View Replies View Related

Which Iterator To Be Use To Create Instances From Feature Value Pairs (Mallet API)

Mar 12, 2015

I am tring to run LDA to generate some topics from txt files as the following one:

Document1 label1 forest=3.4 tree=5 wood=2.85 hammer=1 colour=1 leaf=1.5
Document2 label2 forest=10 tree=5 wood=2.75 hammer=1 colour=4 leaf=1
Document3 label3 forest=19 tree=0.90 wood=2 hammer=2 colour=9 leaf=4.3
Document4 label4 forest=4 tree=5 wood=10 hammer=1 colour=6 leaf=3

Each numeric value in the file is an indication of the number of occurrences of each feature (e.g., forest, tree) multiplied by a given penalty. To generate instances from such a file, I use the following Java code:

String lineRegex = "^(S*)[s,]*(S*)[s,]*(.*)$";
String dataRegex = "[p{L}([0-9]*.[0-9]+|[0-9]+)_=]+";
InstanceList generateInstances(String dataPath) throws UnsupportedEncodingException, FileNotFoundException {
ArrayList<Pipe> pipeList = new ArrayList<Pipe>();
pipeList.add(new Target2Label());

[Code] .....

I then add the so-generated instances to my model using the instruction model.addInstances(generatedInstances). The resulting output is described below.

It contains errors caused by the instruction model.addInstances(generatedInstances). Debugging my code showed me that the alphabet associated to the model is null. Am I using the wrong iterator?

name: document1
target: label1
input: TokenSequence [forest=3.4 feature(forest)=3.4 span[0..10], tree=5 feature(tree)=5.0 span[11..17], wood=2.85 feature(wood)=2.85 span[18..27], hammer=1 feature(hammer)=1.0 span[28..36], colour=1 feature(colour)=1.0 span[37..45], leaf=1.5 feature(leaf)=1.5 span[46..54]]
Token#0:forest=3.4 feature(forest)=3.4 span[0..10]

[Code] ....

View Replies View Related

Print A Blank Line After Certain Specific Points In Iterator

Feb 17, 2015

I have the following HashMap:

// 2009
nobelPrizeWinners.put("2009 Physics",
new PrizeWinner[] {new PrizeWinner("Charles K.", "Kao"),
new PrizeWinner("Willard S.", "Boyle"), new PrizeWinner("George S.", "Smith")});
nobelPrizeWinners.put("2009 Chemistry",
new PrizeWinner[] {new PrizeWinner("Venkatraman", "Ramakrishnan"),

[Code] .....

At the moment, my output is:

2008: Chemistry: Osamu Shimomura, Martin Chalfie, Roger Y. Tsien
2008: Economics: Paul Krugman
2008: Literature: Jean-Marie Gustave Le Clézio
2008: Medicine: Harald zur Hausen, Françoise Barré-Sinoussi, Luc Montagnier
2008: Peace: Martti Ahtisaari

[Code] .....

However, I need a blank line between the final entry of 2008 and the first entry of 2009.

View Replies View Related

Double Circular Linked List - Implementing Iterator

Oct 14, 2014

My homework is a Double Circular Link list and when i write implements Iterator it gives me a an error when I compile it the same for my subset method...

ERRORS :DoublyCircularList.java:55: error: DoublyCircularList.iterator is not abstract and does not override abstract method remove() in Iterator public class iterator implements Iterator<T>
^
Note: DoublyCircularList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

import java.util.Iterator;
public class DoublyCircularList<T extends Comparable<T>> extends LinkedList<T>implements Iterable<T>
{
Node<T> first;
int size;
public DoublyCircularList(){
first = null;
size = 0;

[code]....

View Replies View Related

List Iterator Execution - Traversing In Forward Direction

Nov 5, 2014

List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
list.add(i * 3);
}
ListIterator<Integer> listItr = list.listIterator();
System.out.println("Traversing in a forward direction");

[Code] ....

Output:--

Traversing in a forward direction
0 3 6 9 12
Traversing in a backward direction
12 9 6 3 0 425

Why 425 is not showing when we are traversing in a forward direction.

View Replies View Related

HashSet And Iterator - Accessing Element Contained In The Object?

Sep 23, 2014

I'm not new to java but i'm not able to solve the following issue: I have  a class

public class Localizzazioni implements java.io.Serializable {
private <complexType>  id;
public getId().......
public setId().....

The complexType is a class defined in the code somewhere. Now I want to access it in another class I have
 
Set localizzazioni = new HashSet(0);
localizzazioni=opere.getOiLocalizzazioneOperas();    -- this object give an object of tyoe HashSet
for(Object object : localizzazioni) {
  object.get.........     // i cannot use any method defined in the class Localizzazioni
}

Why I cannot write inside the for object.getId() and using it?? In other word how i can access the element contained in the object?? the object is an iterator of type Localizzazioni . The class Localizzazioni  has some method but i cannot use them? why ....

View Replies View Related

Method That Return Instance Of A Class That Implement Iterator Interface

Apr 14, 2015

I have been researching the Iterator and making a class implement iterable. I have seen this example shown below and was wondering how I could change this so that iterable() is not called upon in the main. I would like to be able to make a method that returns an instance of a class that implements the Iterator interface hopefully an inner class. This is because my program will not have a main and will be supplied with a main that includes a new Object with will use the iterator method.

import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");

[Code] ....

This is all I have been able to understand from what I want to do. This does not work and this is what I am trying to achieve

public class MyArrayList implements Iterable {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
 
[Code] ...

View Replies View Related

Create Own ArrayList Using Collection Without Implementing ArrayList Itself

Feb 28, 2014

I'm trying to create my own arraylist using Collection. My program doesn't do anything. Obviously, I haven't a clue.

import java.util.Collection;
import java.util.Iterator;
public class MyArrayList<T> implements java.util.Collection<T> {
private int size = 4;
private T[] mArray;
public MyArrayList(String[] args) {

[Code] ....

View Replies View Related

Populating ArrayList Object With Nested ArrayList Object

Jul 8, 2014

I have stumbled onto a problem with ArrayLists (not sure if nested ArrayList objects would be a more accurate description) ....

As simply put as I can describe it, I have an Inventory class which creates an ArrayList of a Product superclass, which has two subclasses, PerishableProduct and ItemisedProduct.

By default, the program is meant to have a starting inventory, which is why I have added them in the constructor

public class Inventory {
private List<Product> products;
public Inventory() {
addProduct(new Product("Frying pan", 15, 20));
addProduct(new PerishableProduct("Apple", 5.8, 30, 7));
addProduct(new ItemisedProduct("Cereal", 5.8, 0));
// this is where I am having problems. Wanting to add
// objects to the ItemisedProduct's ArrayList for cereal.
}

Within the ItemisedProduct subclass is yet another ArrayList which is meant to hold serial numbers.

public class ItemisedProduct extends Product {
private ArrayList<String> serialNumbers = new ArrayList();
public ItemisedProduct(String name, double price, int qty) {
super(name, price, qty)

[Code] .....

My problem is that I do not know how to populate the serialNumbers ArrayList from the Inventory class' constructor. Because technically, quantity is defined by how many serial numbers are created.

View Replies View Related

If Then For ArrayList?

Feb 26, 2015

I think it's a problem with my if then else statements but I'm not sure?

package Hw1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; 
 public class ScrapWork {
public static void main(String[] args){
String[]Dalton={"Joe","William","Jack","Averell"};
 
[Code] .....
 
run:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of type
at Hw1.ScrapWork.main(ScrapWork.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

View Replies View Related

Max And Min In ArrayList

Nov 14, 2014

I have an ArrayList with String, String, Double.

From another class I would like to print minimum and maximum including the first String name.

I have tried with import java.util.Collections; but that didn't work.

Java Code:

ArrayList<List>list = new ArrayList<List>();
list.add(new List("Abc","Cba",1));
list.add(new List("Bca","Bca",5));
list.add(new List("Cba","AcB",2)); mh_sh_highlight_all('java');

I would like the result to look like:

Minimum: Abc 1
Maximum: Bca 5

View Replies View Related

How To Use ArrayList With Array

Jun 2, 2014

Something like ArrayList<Object>[] = new ArrayList<Object>[]();

View Replies View Related

How To Order Two ArrayList In One

Feb 14, 2015

I have an ArrayList of employee and ArrayLsit of bosses, and I want to keep those people in a temporary ArrayList , then ordain alphabetically by name, to sort I use the interface comparator.

The problem comes when I will order 2 ArrayList(workers and bosses), because every time I call I use these functions or not is ordered (sortByNameAlphabetical())

public class Employee {
private String name;
public String getName() {
return name;
}
@Override
public String toString() {
return name ;

[Code]...

View Replies View Related

How To Add In Arraylist Of Object

Apr 7, 2015

I'm creating a card game assignment... so i have an arraylist called cards that has 20 cards and every card has contains 2 objects, suit and the point Value.

I shuffled the deck, now i want to add half of it to player 1 and the rest of the cards goes to the bot or computer.

how can i add the cards to the player one arraylist and have all the information of the cards?

here is my Deck class code :-

public class Deck {
private ArrayList cards;
private int size;
private ArrayList player1;
private ArrayList bot;

[code]....

the problem i have is this one doesn't work

size = cards.size() / 2;
for (int i = 0; i < size - 1; i++) {
player1.add(cards.get(i));
}
for (int s = size; s < cards.size() - 1; s++) {
bot.add(cards.get(s));
}

View Replies View Related

Using GUI With Buttons And ArrayList

Sep 18, 2014

Right now, i'm trying to do is when a user clicks on my GUI button, it would display a text of information on the button they selected. I'm using an arraylist of objects and i'm trying to input the function inside the mouse click function. But I'm not sure how to properly display that information. Here is my GUI code. I'm working on the raven button. I have animal interface, with a parent class of Bird, and child class of Raven. How I could display this correctly...

public class AnimalJF extends JFrame {
private JPanel contentPane;
private JTextArea textArea = new JTextArea();
/**
* Launch the application.
*/
public static ArrayList<Bird> Birdlist = new ArrayList<Bird>();
public static void main(String[] args) {
Birdlist.add(new Eagle());

[Code] .....

View Replies View Related

Reading From TXT To ArrayList?

Nov 21, 2014

I am currently working on a program that will read from a .txt file to create an arraylist. I will be working with the objects in the list to perform computations and display the data. The .txt file is in the following format: lastName firstName hoursWorked hourlyRate

With no delimiters. I've messed with this thing way too much in the last 12 hours (only day off for the week ) so variable names etc have changed often. At present the error I am receiving is "error: constructor GrossPayService in class GrossPayService cannot be applied to given types".

import java.util.*;
import java.io.*;
import java.text.*;
class AryListObjects
{
public static void addEmployee(String firstName, String lastName, double hoursWorked, double hourlyRate)
{
ArrayList<GrossPayService> employees = new ArrayList<GrossPayService>();

[code]....

View Replies View Related

Delete From ArrayList

Dec 7, 2014

I've this "program" that shall manage to register a dog, show a list of all registerd dogs and delete dogs from the list.. And I'm stuck at the latter one. So I've to classes, one for the dog and one for register/program. This is my main program

package hundRegister;
import java.util.Scanner;
import java.util.ArrayList;
public class HundProgram {
private static Scanner tangentbord = new Scanner (System.in);
private static ArrayList<Hund> hundlista = new ArrayList<>();

[Code] ......

So, when I enter a name on a dog that exist on my list, it just jumps down to } else { and write that dog can't be found even if I write the exact name on the dog.

I can't see what I'm doing wrong, been trying out different methods now.

View Replies View Related

How To Use Array Instead Of ArrayList

Apr 3, 2014

I'm making a program for my class's chapter on classes. I need to make a program that makes a grocery list using an array. Here's the assignment from the book.

Write a class named GroceryList that represents a list of items to buy from the market, and another class named
GroceryItemOrder that represents a request to purchase a particular item in a given quantity (example: four boxes
of cookies). The GroceryList class should use an array field to store the grocery items and to keep track of its size
(number of items in the list so far). Assume that a grocery list will have no more than 10 items. A GroceryList
object should have the following methods:

public GroceryList()
Constructs a new empty grocery list.
public void add(GroceryItemOrder item)
Adds the given item order to this list if the list has fewer than 10 items.
public double getTotalCost()
Returns the total sum cost of all grocery item orders in this list.

The GroceryItemOrder class should store an item quantity and a price per unit. A GroceryItemOrder object
should have the following methods:

public GroceryItemOrder(String name, int quantity, double pricePerUnit)
Constructs an item order to purchase the item with the given name, in the given quantity, which costs the given price
per unit.
public double getCost()
Returns the total cost of this item in its given quantity. For example, four boxes of cookies that cost 2.30 per unit
have a total cost of 9.20.
public void setQuantity(int quantity)
Sets this grocery item’s quantity to be the given value.

I have the assignment mostly done, but the JUnit test case our teacher gave us to test it tests add() an array instead of an array list. For this reason, I need to change my program to use an array. My code is below.

import java.util.*;
public class GroceryList {
private ArrayList<GroceryItemOrder> list;
int num;
public GroceryList() {
list = new ArrayList<GroceryItemOrder>(10);

[Code] .....

View Replies View Related

How To Sort ArrayList

Jun 30, 2014

How can i sort my ArrayList, which contains cars, with year and used year, i want to sort them first from year, and then from used year . what should i use?

View Replies View Related

Everything In ArrayList Written Twice

Mar 1, 2014

I am trying to read a file into an array list, change some things about it, and then write it to another file. Files are getting written with what was read repeating a second time. I've tested the read method by having it print everything which goes into the ArrayList object. I then did the same with the write method which seems to write everything twice, as if everything is in the ArrayList twice, but I'm not sure how this is possible, since the read clearly did everything only once. Perhaps the ArrayList isn't the best collection to use for this purpose.

The read method:

Java Code:

private ArrayList<String> read(File in) {
String line;
ArrayList<String> data = new ArrayList<String>();
try {
BufferedReader r = new BufferedReader(new FileReader(in));

[code]....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved