I'm writing a program in java and i need to make a list whose nodes are another list . My code for the nodes of the sub list is this :
public class Page {
private String word;
private int num;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Page(String word, int num) {
this.word = word;
this.num = num;
}
}
My code for the nodes of my main list is :
import java.util.ArrayList;
public class IndPage {
private ArrayList<Page> Eggrafi;
//private ArrayList<Page> Eggrafi = new ArrayList<Page>();
public IndPage(String name, int bytes) {
Eggrafi = new ArrayList<Page>();
Eggrafi.add(new Page(name, bytes));
}
public ArrayList<Page> getEggrafi() {
return Eggrafi;
}
public void setEggrafi(ArrayList<Page> eggrafi) {
Eggrafi = eggrafi;
}
}
When i use in my main the following code to fill my list i get a java heap space exception:
if(Index.size()!=0){
for(int j=0;j<Index.size();j++){
for(int y=0;y<Index.get(j).getEggrafi().size();y++){
if((Index.get(j).getEggrafi().get(y).getWord()).equals(tokens[i-1])){
Index.get(j).getEggrafi().add(new Page(fileName[k],byte_count));
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
}
}
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
Also my main list is declared this way :
List<IndPage> Index = new ArrayList<IndPage>();
I've tried many things but still getting the java heap space exception .
Your issue is in your for loop:
for(int j=0;j<Index.size();j++){
for(int y=0;y<Index.get(j).getEggrafi().size();y++){
if((Index.get(j).getEggrafi().get(y).getWord()).equals(tokens[i-1])){
Index.get(j).getEggrafi().add(new Page(fileName[k],byte_count));
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
}
}
Your for loops are doing a check against the lists .size() function you are adding new items to those lists, so the .size() will always be at least 1 more than either the j or y index variables and the loops will never terminate. That eventually is running you out of heap space. The Index.size() and Index.get(j).getEggrafi().size() values are recalculated each time by the for loop, they are not cached.
I think you code is allocating a new list for every insert.
import java.util.List;
import java.util.ArrayList;
public class IndPage {
private List<Page> Eggrafi = new ArrayList<Page>();
public IndPage(final String name, final int bytes) {
Eggrafi.add(new Page(name, bytes));
}
public List<Page> getEggrafi() {
return Eggrafi;
}
public void setEggrafi(final List<Page> eggrafi) {
Eggrafi = eggrafi;
}
}
The code for the loops can be improved by using Java 5 style collection loops ie:
for (final Page page : Eggrafi) {
...
}
Related
Are there any cases in which getFirst() and getLast() show the same element when using the LinkedList provided by Collections?
I am parsing data to staging variables to be held; then I am storing these variables in a new object to be stored in my LinkedList using the add() method. However, when I am printing out statements, after every time an object is added to my LinkedList, by using the getFirst() and getLast() they are pointing to the same object?
Please see code below (please dont critic the code too much, I am only a beginner so I know it isn't pretty, but it recreates my problem)
public class Main {
public static void main(String[] args) {
Parse parse = new Parse();
parse.main();
}
}
import java.lang.reflect.Array;
public class Parse {
String[] input = {"1", "a",
"2", "b",
"3","c",
"4", "d"};
Object tempObject = new Object();
String tempLength;
String tempFilename;
int arrayIndex = 0;
public static ObjectList objectList = new ObjectList();
Parse(){
}
public void main() {
for (int i = 0; i != input.length; i++) {
String stringInput = iterateInputArray(input, i);
addToTempObject(stringInput);
Object finalObject = new Object();
finalObject = tempObject;
Object tempObject = new Object();
objectList.addToList(finalObject);
System.out.println("First:" + ObjectList.listOfObjects.getFirst());
System.out.println("Last:" + ObjectList.listOfObjects.getLast());
}
}
public String iterateInputArray(String[] input, int arrayIndex){
String string = input[arrayIndex];
return string;
}
private void addToTempObject(String inputString){
if (tempLength == null){
tempLength = inputString;
tempObject.setLength(inputString);
}
else {
tempObject.setFilename(inputString);
tempFilename = inputString;
resetTempVariables();
}
}
private void resetTempVariables() {
tempLength = null;
tempFilename = null;
}
}
public class Object {
private String length;
private String filename;
public Object( String length, String filename) {
this.length = length;
this.filename = filename;
}
public Object(){
this.length = null;
this.filename = null;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setLength(String length) {
this.length = length;
}
public String getLength() {
return this.length;
}
public String getFilename() {
return this.filename;
}
}
import java.util.LinkedList;
public class ObjectList extends Object {
public static LinkedList<java.lang.Object> listOfObjects = new
LinkedList<java.lang.Object>();
public ObjectList() {
}
public void addToList(Object object){
listOfObjects.add(object);
}
}
I reduced the code. The reduced code is, for the discussion of the prorblem, identical to the provided code:
import java.util.LinkedList;
class Scratch {
public static final Object tempObject = new Object();
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
The code keeps adding one and the same object (tempObject) to the list. Notice the final keyword introduced to highlight that variable tempObject references the same object over its whole lifetime. Thus, the size of the list grows, but the list contains the same object, over and over again. This is why getFirst() and getLast() return the same object.
The problem can be fixed by, e.g., moving the declaration of tempObject in the loop:
import java.util.LinkedList;
class Scratch {
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
final Object tempObject = new Object();
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
yes, a linked list with one element. like following test
import static org.assertj.core.api.Assertions.assertThat
class ListSpec extends Specification{
def "linked list with one elem"(){
given: "a linked list with one element"
LinkedList<String> list = new LinkedList<>()
list.add("test")
expect:"last and first element are same"
assertThat(list.getFirst()).isEqualTo(list.getLast())
}
}
I am new with java and I need to save the content of a stack of objects into an array which will have an array attribute and also the array attribute has an array attribute I know it kind complicated but I need to do that because it's looks like a table. Anyway, this is my code
//First class
public static class classA //inner
{ public char sy;
public ArrayList <Integer> arrystateA;
public classA()
{ sy='0';
arrystateA= new ArrayList <Integer>();} }
//The second class
public static class ArrayofclassA// meddile
{ int num;
public ArrayList <classA> arrystateB;
public ArrayofclassA()
{ arrystateB=new ArrayList < classA>();
num=-1;}
public void creatrans(classA z)
{ arrystateB.add(z);
} }
and this the main code
classA temp2=new classA();
ArrayofclassA temp3 = new ArrayofclassA();
ArrayList<ArrayofclassA> NFAtranstable=new ArrayList<ArrayofclassA>();
while(!reslt.empty()){
temp=reslt.pop();
for (int i=0;i<NFAtranstable.size();i++)
{temp3=NFAtranstable.get(i);
if (temp3.num==temp.s_to)
{
if(temp3.arrystateB.get(i).sy==temp.t_sym)
{
temp3.arrystateB.get(i).arrystateA.add(temp.s_to);
match=true;
}else
{temp2.sy=temp.t_sym;temp2.arrystateA.add(temp.s_to);
temp3.creatrans(temp2);
match=true;
}
}
}
if(!match)
{
temp2.sy=temp.t_sym;
temp2.arrystateA.add(temp.s_to);
temp3.num=temp.s_from;
temp3.arrystateB.add(temp2);
NFAtranstable.add(temp3);
}
match=false;
}
for(int i=0;i<NFAtranstable.size();i++)
{
System.out.print(NFAtranstable.get(i).num+" ");
for(int j=0;j<NFAtranstable.get(i).arrystateB.size();j++)
{
System.out.println(NFAtranstable.get(i).arrystateB.get(j).sy+" ");
for(int k=0;k<NFAtranstable.get(i).arrystateB.get(j).arrystateA.size();k++)
{
System.out.print(NFAtranstable.get(i).arrystateB.get(j).arrystateA.get(k));
}
}
}
}
the problem that when I print the content of the array 'NFAtranstable' it's gives me duplicate results like it just save the same valus, it's been about 8 hours and I couldn't find the problem =(
I have a problem with this code. My purpose is to create a Dictionary that counts the frequency of a word in a text, using an Array of Objects (I can't use Hash Map or something else). I created a class Pair that contains the couple (word,count).
public class Pair
{ public String word;
public int count;
public Pair(String word,int count)
{this.word=word;
this.count=count;
}
public String getWord()
{return word;}
public int getCount()
{return count;}
public void addCount()
{count++;}
public String toString()
{ return getWord()+" "+getCount();}
}
And the class Dict that creates an Array of object using the Pair class
public class Dict
{ private Pair [] a;
private int inputSize;
public Dict()
{a=new Pair[10];
inputSize=0;
}
public void insert(Pair x)
{ if(a.length==inputSize)
{ Pair newA []=new Pair [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // i check if x is already in the array if i find it i replace it otherwise i add it in the array
{ if(a[i].getWord().equals(x.getWord()))
{a[i]=x;
}
}
a[inputSize++]=x;
}
public Pair find(Pair x) // if i don't find x return null
{ for(int i=0;i<inputSize;i++)
{ if(a[i].getWord().equals(x.getWord()))
{return a[i];}
}
return null;
}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{ s=s+a[i].toString()+'\n';
}
return s;
}
}
After I created the test class with the main method
import java.util.*;
import java.io.*;
public class MyDict
{public static void main(String [] args)
{ Dict d=new Dict();
Scanner c=new Scanner(System.in);
while(c.hasNext())
{String s=c.next();
Pair p=new Pair(s,1); // create a new pair
Pair previous=d.find(p);
if(previous!=null) //if the pair is already in the stack i add 1 to the counter otherwise i insert it in the array
{p.count++;}
else
{d.insert(p);}
s="";
}
System.out.println(d);
}
}
But it doesn't work, in particular the variable "count" doesn't grow.
For example, if I write "how how are are you you " I get:
how 1
are 1
you 1
Can anyone help me please?
Change p.count++ to previous.count++.
Otherwise you never change the count of the existing Pairs.
Pair p=new Pair(s,1);
Pair previous=d.find(p);
if(previous!=null) {
previous.count++;
} else {
d.insert(p);
}
I need to take a collection of objects using the CompareTo() command, and then have these stored in a list, and then use the collections.sort() command to sort them alphabetically by last name, then by first name if the last name isn't strong enough, and then print off the entire list at the end.
This is the code I have so far:
package sortlab;
import java.io.*;
import java.util.*;
public class SortLab {
public static void main(String[] args) throws Exception {
File youSaidUseOurRelativeFileNameForStudentData =
new File("C:/My192/SortLabProj/src/sortlab/student.data");
Scanner sc = new Scanner(youSaidUseOurRelativeFileNameForStudentData);
ArrayList<Student> StudentList = new ArrayList<Student>();
while (sc.hasNextLine()) {
Student testStudent = new Student(sc.next(), sc.next(), sc.next());
sc.nextLine();
StudentList.add(testStudent);
}
}
}
And the next class:
package sortlab;
import java.util.*;
class Student implements Comparable<Student> {
private String first;
private String last;
private String address;
public Student(String f, String l, String a) {
first = f;
last = l;
address = a;
}
#Override
public int compareTo(Student other) {
if (last.hashCode() > other.last.hashCode()) return 1;
if (last.hashCode() < other.last.hashCode()) return -1;
if (first.hashCode() > other.first.hashCode()) return 1;
if (first.hashCode() < other.first.hashCode()) return -1;
return 0;
}
}
If you want to compare them ASCIIbetically use the String.compareTo method. It would never occur to me to compare hashCodes.
If you want to ignore case, you can use String.compareToIgnoreCase
First of all I would add getters for first and last name. Then try this code:
#Override
public int compareTo(Student other) {
int result = l.compareTo(other.getLastName());
if (result == 0) {
return f.compareTo(other.getFirstName());
} else {
return result;
}
}
Then add a toString() method to your Student class:
#Override
public String toString() {
return f+" "+l+", "+a;
}
I am trying to build a simple generic class that uses generic objects in java. everything compiles fine, but when i run the code, it doesn't display the objects i passed to it.
Here is my code:
public class ListDriver {
public static void main(String[] args) {
List<String> glist = new List<String>(10);
glist.add("milk");
glist.add("eggs");
System.out.println("Grocery List" + glist.toString());
}
public class List<T> {
private T[] datastore;
private int size;
private int pos;
public List(int numElements) {
size = numElements;
pos = 0;
datastore = (T[]) new Object[size];
}
public void add(T element) {
datastore[pos] = element;
}
public String toString() {
String elements = "";
for (int i = 0; i < pos; ++i) {
elements += datastore[i] + "";
}
return elements;
}
}
}
You don't increment your pos variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Your add method always replaces the element in position 0 (zero). You forgot to increment pos (pos++;)