Accesing a static ArrayList from another class in Java - java

The ArrayList needs to be set to static. I created a getter method in the main class (CityMenuCreate).In the second class, I do call the method and when I try to create a for function, it doesn't recognize the list.
The method I created in the first class (CityMenuCreate)
public static ArrayList getCityList() {
return cityList;
}
The part of code I'm trying to call the method in the second class
CityMenuCreate.getCityList();
for(int i=0; i< **cityList.size();** i++) {
}
It gives me an error in the cityList.size();. Is there a syntax problem in the for function?

You're ignoring the return value of CityMenuCreate.getCityList(). You either need to save it to a local variable:
List cityList = CityMenuCreate.getCityList();
for (int i = 0; i < cityList.size(); i++) {
// code
}
Or just use it directly from that method:
for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
// code
}

In the above example, you've declared your getCityList() method as static, not your Arraylist. Hence you cannot access your Arraylist in a static way. You either declare your Arraylist static or in your for loop you call the method like so:
for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
//Your code goes here
}

Related

Shallow copy of object not correctly updating original object

I would like to model a graph, and to do so :
I have a class A that contains a LinkedList of instances of A and has a setter method associated :
class A {
private LinkedList<A> list;
[...]
public setList(LinkedList<A> l) {
this.list = l;
}
}
And in an other class NetA I have a method genCon that takes a LinkedList of instances of A then sets their list attribute to be a shuffled SubList of rlist :
static void genCon (LinkedList<A> rlist) {
for(int i=0; i<rlist.size(); i++) {
A temp = rlist.get(i);
LinkedList<A> slist = new LinkedList<A>(rlist.subList(0, rlist.size()));
temp.setList(slist);
}
}
Then genCon(rlist) is called in main, but altough all the objects of rlist should have their list initialized (and being equal to a shuffled version of rlist) some appear to be empty, with no consistent pattern (i.e. not every n or repeatable pattern), but completely at random.
At first I thought that A temp = rlist.get(i) was not giving me a shallow copy of the object at index i, but the check for identity with == returns true, so, if I am not mistaken that means that both variable hold the same reference and that should not be what is causing the issue?
Then I thought that it might be an optimization issue, maybe eclispe tries to do the operations in parallel and that somehow messes up the initialization at random?
I have tried to process step by step, but I can't seem to find where I messed up.
What did I miss?
Edit :
The main function looks like this :
public static void main(String[] args) {
LinkedList<A> a_list = generateAList(20);
genCon(a_list);
for(int i=0; i<a_list.size(); i++) {
System.out.println(a_list.get(i).toString());
}
}
a_list is correctly initialized. The issue happens in the following loop, when trying to print the objects.
Since it's only for testing main is located in the same class as genCon() atm.
generateAList() looks like this :
static public LinkedList<A> generateAList(int n) {
LinkedList<A> a_list = new LinkedList<A>();
for(int i=0; i<n; i++) {
ap_list.add(A.rand()); // A.rand() is just a static function that return an instance of A with randomly set values and an unitialized list.
}
return ap_list;
}

Setters and getters for Array of LinkedList

I have a class that called Entries that holds my constructor along with its getters and setters.
In a new class, I have :
private LinkedList<Entry>[] Entries = new LinkedList[26];
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}
However, I am receiving errors for my setters and getters. This does not happen when I use a straight array or straight LinkedList, as I've already got this method working for those two in two different classes.
The error messages I'm receiving for both are
The method getNumber() is undefined for the type LinkedList
and The method getNumber() is undefined for the type LinkedList
I don't see why they're undefined as when I've tried doing the same method for a straight Array and a pure LinkedList, they've handled it fine and functioned properly.
If anyone has any suggestions, I would really appreciate it.
Pay close attention to the data type you're iterating over. Because myEntries is defined as a LinkedList<Entry>[], you're pulling out an individual LinkedList<Entry> when you iterate over the array.
It really seems like you don't want the array; instead, just iterate over the list elements directly:
LinkedList<Entry> myEntries = new LinkedList<>();
for(Entry entry : myEntries) {
if(entry.equals(number) {
// logic
}
}
myEntries[i] returns a LinkedList this doesnt have the setNumber method. You need to get the Entry out of the list and then invoke these methods.
myEntries[i].get(index).setNumber(); or myEntries[i].getFirst().setNumber(); etc
You are trying to call your accessors/mutators (getNumber() & setNumber) on the LinkedList instance and since there is no such methods for the LinkedList you will have the reported error.
So either get access to some LinkedList item with get() method that will return an Entry object on which you can call your setter and getter:
public void changeNumber(String number, String numberChange) {
int index = 0; //not sure what this index should be in your case
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].get(index).getNumber().equals(number)){
myEntries[i].get(index).setNumber(numberChange);
break;
}
}
}
Or better if you don't need the LinkedList, may be it is worth dropping you design and only create an Array of Entry:
private Entry[] entries = new Entry[26];
Then your changeNumber() method will be eligible:
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}

seeing if a keyword in one Arraylist is in an element of another Arraylist

I've obtained an ArrayListof string for user inputted keywords now I'm trying to see if those keywords are present in the separate elements of another arraylist which is a catalogue of books. My code is shown below and the compiler keeps saying cannot find symbol when i compile the following code:
edit: i've changed the code as follows
ArrayList<Book> catalogue; //was defined in another class
ArrayList<String> keywords;// was created in a driver class through user input
public ArrayList<String> getTitlesContainingKeyword(String keyword){
ArrayList<String>results = new ArrayList<>();
for (int i = 0; i < keywords.size(); i ++) {
for (int j = 0; j < catalogue.size(); j ++){
if (catalogue.get(j).contains(keywords.get(i))) // the contains in this line is giving the error
{
results.add(j);
}
}
}
return results;
}
it appears that the main problem is that catalogue is a book arraylist and keywords is a string arraylist
You should simply check if the keyword exists or not. Why are you using get method ? Simply pass in the String to the contains, completely.
What I mean to say is:
1. Get the keyword.
2. Check if it indeed is a valid keyword by calling the contains() on your keywords ArrayList. If it returns false, do not proceed to search the catalogues.
3. If it is, go over each catalogue and call its contains to see if the keyword is contained in that catalogue.
Your logic seems to be wrong in the code snippet.
public String getTitlesContainingKeyword(String keyword){
for (int i = 0; i < keywords.size(); i ++) {
for (int j = 0; j < catalogue.size(); j ++){
if (catalogue.get(j).contains(keywords.get(i))) {
results.add(j); // << who is results
}
}
}
return results;
}
The error is being given by the compiler because you havn't declared results in your method. Compiler doesn't know what is this results, neither do you, nor me.
If it is supposed be an ArrayList<String>, then declare and create it as such.
Change your method return type to ArrayList<String> instead of String
public ArrayList<String> getTitlesContainingKeyword(String keyword){
ArrayList<String>results = new ArrayList<>();
for (int i = 0; i < keywords.size(); i ++) {
for (String catLog: catalogue){
if (catLog.contains(keywords.get(i))) {
results.add(catLog);
}
}
}
return results;
}

Initialising/Creating Objects through a constructor

Ok so I'm doing an assignment for my java coursets part I'm stuck at is :
"Implement an operation createparliamentMembers which will create the particular Parliament
with 80 members."
So i've already created the constructor with it's methods. This is how I wrote the operation to create the objects using the constructor.:
public static void createparliamentMembers(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
The problem is the arrays and objects only seem to exist in the operation for creating them and when I try running method of the objects created they don't work because the driver class doesn't recognize the arrays. On the other hand when I use this as just a normal part of the Driver for it runs fine and all methods of the objects work normally.
Edit: Ok so I'm still getting the same problem as before even though i initiliased them outside the createparliamentMembers();
The following code is the Driver im using to test the methods: It keeps saying there is a:
Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:11)
which is the code array[1].FlipCoin(); as im trying to use the method flipcoin from the created objects but it's not working.
public static void main(String [] args) {
Commands.createparliamentMembers();
array[1].FlipCoin();
}
Your arrays are only defined locally, which means they live and die with the method. When your method finishes, they get put out of memory.
The solution is to define these arrays as instance variables. By that I mean, you need to define the arrays for your class, and then use them in your method:
class someClass {
int[] myArray = new int[2];
private void someMethod() {
myArray[0] = 3;
myArray[1] = //whatever
}
}
You state in comment:
I do have a parliament class it's on it own and contains the methods and constructor for the members of the parliament. The above method was in a seprate class called Commands. I don't understand completely the "Can you add the members to a Parliament object as you create them?" The parliament isn't an object more se then a class containing a constructor and methods for parliament members i want to create.
Parliament isn't an object yet, but you should in fact create one, and in fact your instructions tell you just that: "which will create the particular Parliament with 80 members...". You will need to tell us more about your program's structure and your specific requirements, but I suggest:
First create a Parliament object in the createParliamentMembers method, and call it parliament.
Then create the members of parliament in that method.
As you create these members, add them to the Parliament object, parliament.
At the end of the method return the parliament variable.
This means that your createParliamentMembers method's signature must change so that rather than return void it should be written to return a Parliament object.
When calling the method in the main method, assign what it returns to a Parliament variable that is in the main method.
It looks like you are writing a factory method. Create a constructor for Parliament like this:
public Parliament(Member[] members, Legislator[] legislators, Leader[] leaders) {
// do whatever with what's passed in
}
Then change your method to return a Parliament object and in the method pass your initialized arrays into the Parliament constructor, like this:
// same code as your except the last line
public static Parliament createParliament(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
return new Parliament(array, leg, lead);
}

printing a string from an array

Write a static method named listCountriesOfOrigin, to be added to the Bowl class, which is passed an array of Bowl objects, and prints to the console in a column the country of origin of each of Bowl objects in the array.
This is my code but is not right and the only compilation errors I am getting is "The system has detected compilation errors." So it is not helping me much. Am i on the right path?
public static String listCountriesOfOrigin (Bowl[] bowls) {
for(int i = 0; i < Bowl.length; i++) {
String origin = bowls[i].getOrigin();
return origin;
}
}
(.getOrigin) is already a declared method that returns the origins of the objects from the array.
for(int i = 0; i < Bowl.length; i++) // `Bowl` is the object name
shouldn't this be
for(int i = 0; i < bowls.length; i++) // bowls is the name of the array of Bowl objects passed to your method.
Also there should not be a return statement inside your for. According to your requirements, your method should print those values on the console.
Hence, make your method return void and instead of the return in the for loop, have a System.out.println(origin);

Categories