I am new to JAVA and found some of its concepts very irritating and no matter how hard I try I can not find suitable explanation for this behavior...of course there are wor around for these problems but still I want to know am I missing something very simple here or JAVA is like this???
I have a string array in one of my class A and I want it to be filled through a method of another class B...so I create an object of class B into A and call the method B.xyz and equate it to the string arra but BOOM I can't do it....java throws a nullpointer exception..........I dont know why...
.
public class B{
public void xyz() {
String[] mystrings=new String[70];
for(int i=0;i<5;i++)
mystrings[i]=value;
return mystrings;
}
}
public class A {
public void abc() {
B b=new B();
String[] StringList;
StringList=b.xyz();
System.out.println(StringList.length);
}
}
I have a similar code fragment now sadly the length of the StrinList becomes 70....if I want to print all the strings of this array I dont have any other way....remember even though the size of mystring is 70 in class B only 5 of its components are properly initialized........SO considering I am in class A and have no way to find out how many times did the for loop in B executed......how do I accurately loop through all the elements of StringList in A.........
PS: There are workarounds to solve this problem but I wanted to know why this happens,i.e, why the length attribute doesn't change according to the components initialized??
If you only need an array of length 5 then only initialize it as that size, e.g.:
public String[] xyz(String value) {
String[] mystrings = new String[5];
for (int i = 0; i < mystrings.length; i++) {
mystrings[i] = value;
}
return mystrings;
}
If you want an array that you can expand you should consider using ArrayList instead. E.g.:
public List<String> abc(String value) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(value);
}
return list;
}
Then you can get its size, add to it and print the elements like this:
List<String> list = abc("foo");
System.out.println(list.size());
list.add("bar");
for (String value : list) {
System.out.println(value);
}
Hope that helps.
You declared xyz as a method with return type void in class B. Presumably you want a signature that returns a string array, public String[] xyz()
Also you didn't declare the array correctly in B, the correct declaration is:
String[] myStrings = new String[70];
-- Dan
String[] mystrings = new String[5];
I suggest you look at using List like ArrayList as this wraps arrays to make them easier to use.
String[] mystrings[70];
This creates an array or arrays. There are two []
I suggest you try instead.
String[] mystrings = new String[5];
Related
I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[]=str;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<str.length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<str.length; i++) {
strTmp[i]=str[list.get(i)];
System.out.println(strTmp[i]);
}
}
The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...
You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
String strTmp[] = str;
to
String strTmp[] = new String[str.length];
If you don't want to change the array str. Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));
output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));
This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);
System.out.println("Original array: " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));
Edit: Output from one example run:
Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]
As you can see, the original array is unmodified.
Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction<String[]>):
String[] newStr = list.toArray(String[]::new);
See both code snippets run live in IdeOne.
I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
List<String> list =Arrays.asList(str);
Collections.shuffle(list);
System.out.println(list);
}
I'm doing a java project and I want sort same string array then count how many each car brand have. I am stuck passing an array into int variable. need suggestions. thanks.
public class SortCars {
public static void main(String[] args) {
String[] cars = {"honda", "toyota", "honda", "toyota"};
String[] honda = new String[5];
String[] toyota = new String[5];
int numOfHonda;
int numOfToyota;
for (int i = 0; i < cars.length; i++) {
if (cars[i].equals("numOfHonda")) { //
honda[i] = cars[i];
honda[i] = numOfHonda; // stuck here
numOfHonda++;
}
}
}
}
You seem to have confusion with String and int values. Since you say you are in the beginning week of your programming and From what I understand from the question. This is what you are trying to do:-
public static void main(String[] args) {
String[] cars = {"honda", "toyota", "honda", "toyota"};
String[] honda = new String[5];
String[] toyota = new String[5];
int numOfHonda = 0; // you need to initialize these int variables
int numOfToyota = 0;
for (int i = 0; i < cars.length; i++) {
if (cars[i].equals("honda")) { // if cars has element honda
honda[i] = cars[i]; // putting cars element in honda array
numOfHonda++; //incrementing value of numOfHonda by 1
}
else if(cars[i].equals("toyota")){
toyota[i] = cars[i];
numofToyota++;
}
}
Now Printing numOfHonda and numofToyota will give you the number of Hondas and Toyotas respectively.
Apart from my answer, I would like to address some errors that I found in your code.
int numOfHonda; //initilize your variable. Otherwise you will get compilation error! make it = 0 in this case.
int numOfToyota; // same here, initialize to 0.
if (cars[i].equals("numOfHonda"))
Here you are trying to compare cars[i] element to a string "numOfHonda".If you look at your code there is no such String declared as "numofHonda". There is one thing which is an int type variable
equals() method does not compare int type with String. It always compares String with String. And the fact that you have put your int variable numofHonda inside " " does not make it the same thing! "numofHonda" and numHonda are different things!
honda[i] = numOfHonda;
You were stuck here because you know what you are doing here?
you are trying to put int type variable(numOfHonda is of int type remember?)
inside a String array. This is not possible. It is a type mismatch. The basic definition of Any type of Array is it holds the same type of elements. So honda[] can not store an int type value.
Hope you have a better view now. Keep Learning.
It will be quite simple if you're allowed to use Java 8. Here's the code.
String[] cars = {"honda", "toyota", "honda", "toyota"};
Map<String, Long> data = Arrays.stream(cars)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(data); // => {toyota=2, honda=2}
Use TreeMap- Simple and precise solution
String[] cars = {"honda", "toyota", "honda", "toyota"};
TreeMap<String, Integer> map = new TreeMap<>();
for(String s: cars){
int count = map.containsKey(s) ? map.get(s) : 0;
map.put(s, count+1);
}
System.out.println(map);
output
{honda=2, toyota=2}
So you want to go over an array of cars and sort it into different array depending on there manufacturer? If so, here's my approach:
import java.util.ArrayList;
String[] cars = {"honda", "toyota", "honda", "toyota"};
ArrayList<String> honda = new ArrayList<String>();
ArrayList<String> toyota = new ArrayList<String>();
for (int i = 0; i < cars.length; i++) {
switch(cars[i]) {
case "honda":
honda.add(cars[i]);
break;
case "toyota":
toyota(cars[i]);
break;
}
}
I would suggest to use ArrayList (java.util.ArrayList) much more versatile. Furthermore I would use a switch-statement. And counting the amount of each manufacturer seems unnecessary to me, just check via honda.length.
EDIT: in depth explanation
ArrayList
Okay, so here it is step by step. My Code does not really differs too much from yours. I change the manufacturer array to by ArrayList which is a 'CustomDatatype'. Under the hood it uses an array but it provides us with a few functionalities which make it easier to interact with this array (e.g. the .add() method to easily add an element to the ArrayList). To initialize an ArrayList we need to call the new-keyword since it a class not a basic datatype. We also need to tell the Array what datatype the element inside it have, this is what we to with the angle brackets (ArrayList<ELEMENT_DATATYPE>())
switch()
The switch statement take whatever you 'give' it as the parameter in parentheses and tries to match it with the cases defined in the switch function. If a match is found it runs whatever code is defined by the case. Switch statements also have the ability to have fall through which keeps checking for matches even when the first is found, this can be useful but for now the prevent this with using the break-statement. A proper switch-case also has a default case which will run when no match is found, but this is also left out here due to complexity. (#otherDevs: sue me, I'm trying to explain things)
Conclusion
I tried to show a way using your approach and slightly changing it but in general it is the same, of course there a many ways to solve this stuff like Map and so on. But as you're just starting I recommend going with the basics. AND you really should get familiar with the Java-Docs since having the ability to read and use docs it pure gold as a developer.
My problem is that I have a function that receives a number of ArrayList's, and I want to loop through them all, but I don't know how many they will be, it can be any number of ArrayList's.
Besides, the ArrayList's have different sizes, and their sizes can also be anything.
I could not find people with a similar problem, all I found was people who already knew the number of ArrayList's or the size of the ArrayList's.
Just to illustrate, I will show a possible situation:
class A{
public ArrayList<String> chars = new ArrayList<>();
}
class C{
public ArrayList<A> A_objects = new ArrayList<>();
public void print(){
// Print all combinations of chars from the A_objects
}
}
A a1 = new A();
A a2 = new A();
a1.chars.add("x");
a1.chars.add("y");
a2.chars.add("X");
a2.chars.add("Y");
a2.chars.add("Z");
C c1 = new C();
c1.A_objects.add(a1);
c1.A_objects.add(a2);
c1.print();
What I want is a way to loop through the ArrayList's so that all combinations are made. The function would print, for example:
xX xY xZ yX yY yZ
Note that the print function doesn't know the size of 'A_objects', neither the size of the 'chars' ArrayList's, but it has to loop through them anyway.
Is there a way to accomplish this?
Thank you all for reading, and I'm sorry if I'm doing something wrong, this is just my second question.
I guess you'd need to have some kind of merge method.
For more readability, I will remove the A and C classes to use only lists.
List<String> merge(List<String> first, List<String> second) {
if(first.isEmpty()) {return second;}
if(second.isEmpty()) {return first;}
List<String> result = new ArrayList<>();
for(String prefix : first) {
for(String suffix : second) {
result.add(prefix + suffix);
}
}
return result;
}
and now have a print method :
public void print() {
List<String> all = new ArrayList<>();
for(A element : A_objects) {
all = merge(all, element.chars)
}
// now you just have to print
}
This was not tested but should do the job.
Loop through the first arraylist then for each element of the arraylist loop through the second arraylist.
Example:
for(A singlelist : arraylistoflists)
{
for(String element : singlelist.getYourArrayList())
{
//processing here
}
}
This is just an example you will have to modify to use your class.
You're going to want two nested loops. The first one gets each A in turn, and the second one gets each string in the given A's list of strings. for-each loops make the size not an issue, on both counts.
public void print(){
for(A a : A_objects){
for(String s : a.chars){
System.out.print(s);
}
System.out.print(" ");
}
}
We've not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Main.Main(Main.java:14)
Here is my code
import java.util.ArrayList;
public class Main
{
public static void Main()
{
System.out.println("Test");
ArrayList <Objects> xcoords = new ArrayList<Objects>();
for( int x = 1 ; x < xcoords.size() ; x++ )
{
System.out.println(xcoords.get(x));
}
}
}
And then the class where the ArrayList is
import java.util.ArrayList;
public class Objects
{
public void xco()
{
ArrayList xcoords = new ArrayList();
//X coords
//Destroyable
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
//Static Walls
xcoords.add(600);
xcoords.add(400);
xcoords.add(600);
}
}
If someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.
Thanks in advance.
Strictly speaking, the exception is due to indexing location 1 of an ArrayList with 0 elements. Notice where you start you for loop index variable x. But consider this line:
ArrayList <Objects> xcoords = new ArrayList<Objects>();
xcoords points to a new, empty ArrayList, not the one you created in class Objects. To get that ArrayList, change the method xco like
public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList
ArrayList<Integer> xcoords = new ArrayList<Integer>();
// .. add all the elements ..
return xcoords;
}
then, in your main method
public static void main(String [] args) { // add correct arguments
//..
ArrayList <Integer> xcoords = (new Objects()).xco();
for( int x = 0 ; x < xcoords.size() ; x++ ) { // start from index 0
System.out.println(xcoords.get(x));
}
}
Here you're simply creating two completely unrelated lists. Either have the array list be a property of the Objects class and retrieve it through an instance method, or return it from an instance or static method, or make the property static. IMO the first two are preferable in most situations.
public class Objects {
public static List<Integer> getXcoords() {
List<Integer> xcoords = new ArrayList<Integer>();
// Your same code, but adding:
return xoords;
}
}
Then to use it:
import java.util.ArrayList;
public class Main {
// Note the lower-case "main" here. You want that.
public static void main() {
List<Integer> xcoords = Objects.getXcoords();
// etc.
Also, your List should be of Integer, not of Objects, which would create a collection holding instances of Objects. You may want to take a step back and relate lists to arrays in a better way--you wouldn't create an array of Objects, would you? No, you'd have an array of int or Integer.
Also, there's Arrays.asList.
You have an IndexOutOfBoundsException which means that you are trying to access an element in an array which is not existing.
But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.
But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:
public static void main(String[] args){
Objects myObjects = new Objects();
ArrayList<Integer> listFromMyObjects = myObjects.getList();
for( int x = 0 ; x < listFromMyObjects.size() ; x++ )
{
System.out.println(listFromMyObjects.get(x));
}
}
public class Objects
{
private ArrayList<Integer> myList;
public Objects(){
myList = new ArrayList<Integer>();
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(600);
myList.add(400);
myList.add(600);
}
public ArrayList<Integer> getList(){
return myList;
}
}
In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}