Setting ArrayList items in one Class from another Class - java

There is a foo class with an ArrayList of double msg called msgstoboo as well as a method setMsg(int index, double input) to alter individual messages in msgstoboo.
There is a networkoffoos class with an ArrayList of foo objects called listoffoos. There is an updatefoomsg method:
public void updatefoomsg (ArrayList<ArrayList<Foo>> Foonetwork)
{
for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
Foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,somerandomvalue)
}
The goal of updatefoomsg is to change the values of individual msgs in msgstooboo. However, no values in the foo class ArrayList `msgstoboo' are altered. Why is this and how do I fix it? Thank you in advance.
UPDATE: Here are the whole foo and networkoffoos classes
public class foo
{
ArrayList<Double> msgstoboo = new ArrayList<Double>(Double);
public foo(int numofmessages)
{
for (int i = 0; i < numofmessages; i++)
{
msgstoboo.add(1);
}
}
public void setMsg(int index, double input)
{
msgstoboo.set(index,input);
}
&&
public class networkoffoos
{
ArrayList<ArrayList<foo>> foonetwork = new ArrayList<ArrayList<foo>>();
public void networkoffoos(int numoffoos)
{
for(int i = 0; i < numoffoos; i++)
foonetwork.add(new foo(somenumberofmsgs))
}
//**AND THE "updatefoomsg" method included in this post**
}

The following works for me. Made some small changes because your code wouldn't compile. Hope it helps.
import java.util.ArrayList;
public class test {
private static ArrayList<ArrayList<Foo>> foonetwork = new ArrayList<ArrayList<Foo>>();
public static void main(String[] args){
networkoffoos(5);
updatefoomsg(foonetwork);
}
public static void networkoffoos(int numoffoos) {
for(int i = 0; i < numoffoos; i++) {
ArrayList<Foo> fooArrayList = new ArrayList<Foo>();
fooArrayList.add(new Foo(10));
foonetwork.add(fooArrayList);
}
}
public static void updatefoomsg (ArrayList<ArrayList<Foo>> foonetwork) {
for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,3);
}
}
and your Foo class
import java.util.ArrayList;
public class Foo {
ArrayList<Double> msgstoboo = new ArrayList<Double>();
public Foo(int numofmessages) {
for (int i = 0; i < numofmessages; i++) {
msgstoboo.add(Double.valueOf(1));
}
}
public void setMsg(int index, double input) {
msgstoboo.set(index, input);
}
}

Related

How to pass my object into another objects field?

I am trying to fill UCFCourse courseOne in my constructor with a courses[] object in fillWithCourses().UCFCourse courseOne does populate outside of the constructor but will not go into it.
public class UCFSemester<courses> {
private static UCFCourse courseOne;
private static double totalSemesters;
private static double completionTime;
static boolean fillSemester = true;
public UCFSemester(UCFCourse courseOne, UCFCourse[] coursetwo) {
this.courseOne = courseOne;
}
public static UCFCourse getcourseOne() {
return courseOne;
}
public static void setCoursesone(UCFCourse courses) {
courseOne = courses;
}
public static void fillWithCourses(UCFCourse courses[], int l) {
int x = 0;
while (fillSemester) {
for (int n = 0; n < 5; n++) {
if (x != n && courses[x].getCourseLevel() < courses[n].getCourseLevel()) {
setCoursesone(courses[x]);
}
}
fillSemester = false;
}
}
}
Side question.How can I access this all in a non-static way?I need the entire thing to be non-static but no matter what I do I can't get it.Thanks!
You can simply do it by creating a List like this:
public class UCFSemester {
private List<UCFCourse> courseList = new ArrayList<>();
public UCFCourse getCourse(int index) {
return courseList.get(index);
}
public void addCourses(UCFCourse[] courses) {
for(int x = 0; x < courses.length; x++) {
courseList.add(courses[x]);
}
}
}
Here, I'm assuming that you are passing the UCFCourse[] array with all the course details that are there in that particular semester.
addCourses() function will take this array and then add all the corresponding courses to the List.
getCourse() function will return you any particular course from the List (Using Index). You can also modify the search in any way you want.

How to access an array from another class

I want to operate on the array called "players" that is declared in the main method. I want to use "players" in my class called "Glucksspielthread"
I know that I can't access "players" because it is declared in the main method and is not visible for other classes.
How can I solve this problem? Here is my code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Glucksspieltest {
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
Glucksspielthread[] players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
class Thinker {
public static void think(int Millisekunden) {
try {
Thread.sleep(Millisekunden);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void randomThink(int minMillisekunden, int maxMillisekunden) {
System.out.println("test");
}
}
class Glucksspielthread implements Runnable {
public int playerNumber;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
}
}
}
Just for your test purpose make your players variable static and public in the Glucksspieltest class, like this:
public class Glucksspieltest {
public static Glucksspielthread[] players;
Then acces it in the Glucksspielthread class like this:
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
Glucksspieltest.players
}
Add a method to class Glucksspieltest, and make the players array global:
public class Glucksspieltest {
private static Glucksspielthread[] players;
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
This way you can get the array by calling the getPlayers() method.
(Note that, it would be adviced to add a constructor to initialize and fill the players array, and separate the player management from the main method as well.)
Make players as private global referance variable
public class Glucksspieltest {
//Make a Global reference variable players
private static Glucksspielthread[] players;
// Make a getter Method to get players
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
And access it by Glucksspieltest.getPlayers();
class Glucksspielthread implements Runnable {
public int playerNumber;
private static Glucksspielthread[] players;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
players= Glucksspieltest.getPlayers(); // play with players
}
}
}

cannot cast java.util.concurrent.ForkJoinWorkerThread into java.lang.Thread- Complex structure

I understand the concept of fork/join, but almost all resources over the internet use, Fibonacci as an example, but my scenario is more complex. I sketched the program, and I have an exception as commented in the below code..
Class Test
{
public static void main(String[] args)
{
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
}
Class Train extends RecursiveAction
{
public Train(int d, int n)
{
//some intialization
}
public Train()
{
t= new Train[5];
new Vec().run_Vec(t);
}
#Override
protected void compute() {
for(int i= 1; i< 8; i++)
{
// x, and y are predefined
temp[x][y] = some calculation;
}
}
}
class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}
I think your problem is due to calling fork() from the main thread. When you call p.invoke(new Train()), your default train constructor actually calls the run_vec() and tries to fork(). Upon reading the javadocs, there are examples that fork() is called within compute(). You need to be calling fork from a thread started by p.invoke().
Based on this Java article I made the following code snippet: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveAction.html
You should only call fork (spawn) within a "running" Thread. This means you must pass on the Train array within the compute method:
package ...;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
class ConcurrentTest {
public static void main(String[] args) {
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
public static class Train extends RecursiveAction {
private Train[] t = null;
public Train(int d, int n) {
//some code
}
public Train() {
t= new Train[5];
}
#Override
protected void compute() {
if(t != null) {
new Vec().run_Vec(t);
for(int i= 1; i< 8; i++) {
System.out.println("Test.Train.compute(): " + i);
}
}
}
}
public static class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
System.out.println("Clazz: " + t[i].getClass());
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}

Trying to convert an arraylist of integers into primitive type int[]

I have an arraylist of Integers called stockList.
I want a primitive type of int[] stockListFinal to be made form the arrayList.
Code:
public class Warehouses {
ArrayList<Warehouse> warehouses = new ArrayList<Warehouse>();
ArrayList<Integer> stockList = new ArrayList<Integer>();
ArrayList<String> locationsList = new ArrayList<String>();
int[] stockListFINAL;
int[] locationsListFINAL;
public Warehouses() {
addWarehouses();
stockList();
locationList();
}
public void addWarehouses() {
//DATABASE WOULD BE SEARCHED FOR EACH PRESENT RECORD AND ADDED HERE
//FOR SIMPLICITY I HAVE DONE THIS MANUALLY
warehouses.add(new Warehouse("W1", 20, "RM13 8BB"));
warehouses.add(new Warehouse("W2", 28, "RM13 8BB"));
warehouses.add(new Warehouse("W3", 17, "RM13 8BB"));
}
public void stockList() {
for(Warehouse warehouse : warehouses) {
Integer stock = warehouse.getStock();
}
stockListFINAL = convertIntegers(stockList);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i);
}
return ret;
}
public void locationList() {
for(Warehouse warehouse : warehouses) {
String location = warehouse.getLocation();
}
}
}
class Warehouse
{
private String warehouseID;
private int warehouseStock;
private String location;
/**
* Constructor for objects of class Warehouse
*/
public Warehouse(String warehouseID, int warehouseStock, String location)
{
// initialise instance variables
this.warehouseID = warehouseID;
this.warehouseStock = warehouseStock;
this.location = location;
}
public int getStock(){
return warehouseStock;
}
public String getLocation() {
return location;
}
}
stockListFinal however returns empty.
What has happened here?
If you run main in the class below you'll see the int[] is populated. This isn't how I'd recommend implementing, but I've tried to remain as close to your example as possible:
import java.util.ArrayList;
import java.util.List;
public class SE
{
final static ArrayList<Integer> stockList = new ArrayList<Integer>();
public static int[] convertIntegers(final List<Integer> integers)
{
final int[] ret = new int[integers.size()];
for (int i = 0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
public static void addStock()
{
stockList.add(20);
stockList.add(30);
}
public static void main(final String[] args)
{
addStock();
final int[] stockListFINAL = convertIntegers(stockList);
for (int i = 0; i < stockListFINAL.length; i++)
{
System.out.println(String.format(" For location %d in the int[] the value is %d", i, stockListFINAL[i]));
}
}
}
You didn't call addStock() so the List is empty.
addStock(); // this was missing, and it
// should probably take the
// List as an argument.
int[] stockListFINAL = convertIntegers(stockList);
I then verified with this code
// No change.
public static int[] convertIntegers(
List<Integer> integers) {
int[] ret = new int[integers.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = integers.get(i).intValue();
}
return ret;
}
// Made static, added List as argument.
public static void addStock(List<Integer> stockList) {
stockList.add(20);
stockList.add(30);
}
public static void main(String s[]) {
ArrayList<Integer> stockList = new ArrayList<Integer>();
addStock(stockList);
int[] stockListFINAL = convertIntegers(stockList);
System.out.println(java.util.Arrays.toString(stockListFINAL));
}
And it outputs -
[20, 30]
You never added Stock(s) to your List(s).

Trouble with Sort program using objects and constructors

Really new to java wanted to make my separate sorting methods (they all work hopefully i did them right)
Also very new to objects and constructors hopefully what im talking about is an object
so here are the constructors
public class sort{
public int[] selectsort(int[] num)
{
int j,i,key,min;
for(j = 0; j<num.length; j++)
{
key = num[j];
min = j;
for(i=j+1; i<num.length; i++)
{
if(num[i]<num[min])
{
min = i;
}
}
num[j] = num[min];
num[min] = key;
}
return num;
}
public int[] insertsort(int[] num)
{
int j,i,key;
for(j = 1; j<num.length; j++)
{
key = num[j];
for(i=j-1; i>=0 && num[i]>key; i--)
{
num[i+1]=num[i];
}
num[i+1]=key;
}
return num;
}
public static int[] bubblesort(int[] num)
{
int i,j,ini;
for(i = num.length-1; i>1; i--)
{
for(j=0;j<i; j++)
{
if(num[j]>num[j+1])
{
ini = num[j];
num[j]=num[j+1];
num[j+1]=ini;
}
}
}
return num;
}
}
and the program/test
import java.util.Arrays;
public class sorttest{
public static void main(String[] args)
{
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}
javac sort.java compiles but javac sorttest.java doesnt
error:
sorttest.java:9: cannot find symbol
symbol : method selectsort(int[])
location: class sorttest
System.out.println(Arrays.toString(selectsort(num)));
^
1 error
The method selectsort is not a part of the sorttest class - it's a public static method in the sort class. This means you need to qualify it by its class name:
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(sort.selectsort(num)));
}
}
Alternatively, you could use a static import:
import static sort.selectsort;
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}

Categories