Dynamically initialise array name - java

I am trying to create an array of objects with a MAX_N 6 object into this array, then create another array within an else statement to fit the rest of the array objects.
I would like to name the new array
sbag1
sbag2
etc
here is my code:
public static ShoppingBag[] packIntoBags(GroceryItem[] goods) {
ShoppingBag newBag = new ShoppingBag();
GroceryItem tmpObject = null;
int index = 0;
String bag = "newBag";
String bagNum = bag + index;
for (int i = 0; i < MAXNBAG; i++)
if (newBag.numItems() < MAX_NUM_ITEMS) {
for (int k = 0; i < MAX_NUM_ITEMS; i++) {
tmpObject = goods[i];
newBag.addToBag(tmpObject);
}
}
else {
ShoppingBag newBag1 = new ShoppingBag();
}
}

You will not be able to dynamically create new variables in java.
When I look at the signature of your method you don't need to return multiple variables, only an array of ShoppingBags.
You should create a variable of type List<ShoppingBag>:
List<ShoppingBag> shoppingsBags=new ArrayList<>();
each time you need a new ShoppingBag:
bag=new ShoppingBag();
shoppingBags.add(bag);
at the end convert this list to an array:
return shoppingBags.toArray(new ShoppingBag[0]);

Java is a statically compiled language. In general, it is not possible, or to be precise: not helpful to use "dynamic" names for variables.
What you could do instead: use a Map, or even more simple: an array of arrays to hold your data.

Related

How can i remove an element from array in Java

Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}

Looping in 2D-List JAVA

I'm trying to get the values for my function from the 2D List.
My 2D list value is defined as
List<List<String>> combined2d = new ArrayList<List<String>>();
After adding the values in to my List the structure is like below,
[[62744768, 62536400, 63689012, 63676486], [67888160, 67852422, 67299346, 68149470], [2017-09-06, 2017-09-05, 2017-09-17, 2017-09-15]]
I have a function with 3 parameters i.e,
FuncA(string param1,string param2,string param3)
{
//some operations
}
Now i want to pass the parameters of the FuncA by looping the 2D List Values.
For Loop 1
I have to get the 00,10,20 Index values from the List such as
62477,6780,2017-09-06
So that I will pass the parameters to my FuncA like
FuncA(62477,6780,2017-09-06)
For Loop 2
Like so for Loop 2 ,
FuncA(600,6785,2017-08-05)
For Loop 3
FuncA(12,646,2017-07-17)
Up-to N loops...
For a simple ArrayList I'm able to loop through like this
for(String value:Singlearraylist) {
FuncB(value);
}
As I'm new to java I couldn't able to find the solution for my problem here.
Appreciate your response
JAY
String[] strings = new String[combined2d.size()];
for (int i = 0; i < combined2d.get(0).size(); i++){
for (int j = 0; j < combined2d.size(); j++){
strings[j] = combined2d.get(j).get(i);
}
FuncA(strings[0] strings[1], strings[2]);
}
I think this will work fine for you.
If size of all the Lists are uneven, loop size should be minimum size of all given lists given in the 2-d list. Accordingly code can be written as forllows:
List<List<String>> combined2d = new ArrayList<List<String>>();
int minTemp = Math.min(combined2d.get(0).size(),combined2d.get(1).size());
int min = Math.min(minTemp,combined2d.get(2).size());
for(int i=0; i<min ; i+= 10){
FuncA(combined2d.get(0).get(i), combined2d.get(1).get(i), combined2d.get(2).get(i));
}
As #MadProgrammer suggested, create a class with data members param1 param2 param3with getters and setters and the list of this class's type, which you can use to iterate pass values to FuncA(...,...,...)
class Data{
String param1, param2, param3;
// constructors, getters and setters
}
List<Data> listData = new ArrayList<>();
for(Data temp : listData)FuncA(temp.getParam1(),temp.getParam2(),temp.getParam3());
And the way you create your list is the key here also as #MadProgrammer suggested in the comments.
This way, your code is a lot easier to read and debug.

Copying the first two values of an array into a new array

I have sorted an array of objects into descending order based on one of their variables. I now need to take the first two values of this array and place them in a new String array. What I have so far is below, but Im obviously making a stupid mistake somewhere.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teams[i] = teamsToProgress[i];
}
}
You try to assign String to a Team field (here: teams[i] = teamsToProgress[i];). You'll have to convert (not casting) the String to a Team instance before assigning.
If your just looking for a logical error, here it is:
teams[i] = teamsToProgress[i]; should be replaced to teamsToProgress[i] = teams[i];
I'm not getting into the details of the syntax involved. But I guess this is what you wanted based on your question.
teams[i] = teamsToProgress[i]; should be reversed, this make no sense. You're also missing a return statement.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teamsToProgress[i] = teams[i]; //.getSomething() ?
}
return teamsToProgress;
}
your question is not clear enough as we still need to learn about Team object structure. but I'm guessing you are looking after something like this.
public String[] teamsToProgress(Team[] teams) //pass your sorted teams array as a param.
{
String[] teamsToProgress = new String[2];
for (int i=0; i<2; i++)
{
teamsToProgress[i] = String.valueOf(teams[i]); //convert teams[i] to string
}
return teamsToProgress;// you need to return an array
}

Making an new ArrayList<String> from ArrayList<UserBean> of an bean class

I have an ArrayList of an bean class consisting five fields as
Java Bean -- MyShares
fileName
filePath
fileSize
isShared
Creator
I Want to make a ArrayList of filePath from this arraylist of bean class
I don't have vast knowledge on Java collections. So what will be the shortest logic for this.
The present logic which I have implemented is below, Now I want an optimized Logic to do so
ArrayList<Myshares> fileDetails = new ReadSDCard().getSdCardFiles();
if (!fileDetails.isEmpty()) {
for (int i = 0; i < fileDetails.size(); i++) {
CommonUtilities.filePaths.add(fileDetails.get(i).getPath());
}
}
if (!CommonUtilities.filePaths.isEmpty()) {
for (int i = 0; i < CommonUtilities.filePaths.size(); i++) {
Log.d(Integer.toString(i), CommonUtilities.filePaths.get(i));
}
}
CommonUtilities.filePaths is my static ArrayList in which I want to store the file paths
What you doing is fine but u need to check whether path is null before inserting in CommonUtilities.filePaths. You can also use a iterator instead of for loop.
You can may be avoid two for loops and just do the following:
ArrayList<Myshares> fileDetails = new ReadSDCard().getSdCardFiles();
int j=0;
if (!fileDetails.isEmpty()) {
for (int i = 0; i < fileDetails.size(); i++) {
if(fileDetails.get(i).getPath()!=null){
CommonUtilities.filePaths.add(fileDetails.get(i).getPath());
Log.d(Integer.toString(j), CommonUtilities.filePaths.get(j));
j++;
}
}
}
Im struggeling to understand why you would have two loops. One that loops through the fileDetails collection and add the paths to a new collection, and then you loop through the new collection for logging. Do these two steps in the same loop:
if (!fileDetails.isEmpty()) {
for (int i = 0; i < fileDetails.size(); i++) {
CommonUtilities.filePaths.add(fileDetails.get(i).getPath());
Log.d(Integer.toString(i), fileDetails.get(i).getPath());
}
}
Other then that I cannot see how this could be optimated since it's impossible to add the paths to a new array without looping through the one with fileDetails. This logic will run in O(n) time
Why to use CommonUtilities again to get the file paths ? We can log the path at the same instance while iterating
ArrayList<Myshares> fileDetails = new ReadSDCard().getSdCardFiles();
if (!fileDetails.isEmpty()) {
for (int i = 0,n=fileDetails.size(); i < n; i++) {
CommonUtilities.filePaths.add(fileDetails.get(i).getPath());
Log.d(Integer.toString(i),fileDetails.get(i).getPath());
}
}
Please see the construct :
for (int i = 0,n=fileDetails.size(); i < n; i++)
We can use this , provided , we are sure that fileDetails.size() will return same result (list is not being modified).
This will save us from calling fileDetails.size() each time

couldn't cast an object array to another type array

been pulling my hair for nights when I get an ClassCastException as I try to cast an object type to another object type.... I'm that sure that this code will work because all objects are are subclasses of the Object class... but somehow i get this exception...some help guys?
Sorry guys..not to be confused with the Original ArrayList, I'm learning Java programming, and practicing on casting object arrays... the exception is at line 8, where I casted the object array to a weapon array type... sorry for any form of trolling...
public class ArrayList {
public static void main(String args[]){
ArrayList arrayList = new ArrayList();
weapon[] weapons = new weapon[5];
for (int i = 0; i < weapons.length; i++) {
weapons[i] = new weapon(i);
}
weapons = (weapon[]) arrayList.add(weapons,
new weapon(weapons.length + 1, "mp5"));
}
public Object[] add(Object[] targetObjectList, Object add){
Object[] oldList = new Object[targetObjectList.length];
for (int i = 0 ; i < oldList.length; i++){
oldList[i] = targetObjectList[i];
}
Object[] newList = new Object[oldList.length+1];
for (int i = 0; i < oldList.length; i++) {
newList[i] = oldList[i];
}
newList[newList.length - 1] = add;
return newList;
}
}//end arrayList class
class weapon {
String name;
int id;
public weapon(int id) {
this.id = id;
name = "weapon";
}
public weapon(int id, String name) {
this.id = id;
this.name = name;
}
}
A weapon is an Object; therefore, we may treat an array af weapon as an array of Object. However, not all Objects are weapons; therefore, an array of Object may not be treated as an array of weapon - unless the thing that seems to be an array of Object really was an array of weapon to begin with. Because of this, your approach will become difficult. You could try
weapon[] newList = new weapon[oldList.length+1];
instead, but then you'd need to change all the arrays to be of type weapon[], and the method wouldn't become general (which I suppose is your goal). However, if you want a method that can add an element to any kind of array, you should use generics instead.
P.S. If you are learning about programming and arrays, writing such an add() method is a good exercise - but if you "just want it to work", you should use ArrayList instead, which does the whole job of adding for you.
Arrays are subclass of Object. You cannot cast Object[] to weapon[]. Here is a generic solution for your problem:
weapons = (weapon[])arrayList.add(weapons, new weapon(weapons.length + 1, "mp5"),weapon.class);
and
public <T> T[] add(T[] targetObjectList, T add, Class<T> c) {
T[] oldList = (T[])Array.newInstance(c, targetObjectList.length);
for (int i = 0; i < oldList.length; i++) {
oldList[i] = targetObjectList[i];
}
T[] newList = (T[])Array.newInstance(c, oldList.length + 1);
for (int i = 0; i < oldList.length; i++) {
newList[i] = oldList[i];
}
newList[newList.length - 1] = add;
return newList;
}
Note: Follow Java Naming Conventions. Avoid Java API class names as your class name.
Object o = new Foo(). This is ok. Foo is Object. As Foo extends Object
Foo f = new Object() Not OK, Object is NOT Foo (Compiler error)
Foo f = (Foo)(new Object()) - ClassCastException
What you are looking to do is known as contravariance. The inherent problem in your code is that the ARRAY that you are creating in the add function is an array of Objects (regardless of what those objects actually end up being).
If you were to do the following, your code would work. I think that you need to work with generics in this sense (look at the actual ArrayList class as it already implements this).
...snip...
Object[] newList = new weapon[oldList.length+1];
for (int i = 0; i < oldList.length; i++) {
newList[i] = oldList[i];
}
newList[newList.length - 1] = add;
return newList;
...snip...
Here is an example code that works much as you are anticipating it.
public class Test {
public static void main(String[] args) {
Integer[] i = (Integer[])Test.get();
}
public static Object[] get() {
Object[] o = new Object[20];
for(int i = 0; i < o.length; i++) {
o[i] = new Integer(0);
}
return o;
}
}
ArrayList has a method .toArray(T[] a) which will return an enlarged array size containing your new elements. So how does this contravariance work? Through the java.reflect package. This is a very small excerpt of how it actually works (there are a few different packages that work together to get down to this.)
...Object[] function(Object[] typearray) {
Object[] o = (Object[]) Array.newInstance(typearray.getClass().getComponentType(), 20);
...fill...
return o;
}
The reason you must do this is because the ARRAY (since everything in Java are objects) is an Object itself, then an Array of Objects cannot be upcasted to an Array of Integers. If you downcasted from an array of integers to an array of Objects (as shown in this above example) and then upcasted again from an Array of Objects to an Array of Integers (because we never dropped the underlying class of it being an Array of Integers).

Categories

Resources