I wanted to ask what am I doing wrong that is causing the if statement to be false every time I run the program. I've also tried to use .equals(num) instead of the Array.asList(num) to check if the value is in there, but that caused the for loop to repeat the "Not in database" multiple times.
Arrays.asList(Data) creates a list whose only element is an array of int (i.e. List<int[]>). That's why Arrays.asList(Data).contains(num)) always returns false.
Try changing your array to :
Integer Data[] = new Integer[n];
This will make Arrays.asList(Data) create a list of Integer (List<Integer>) containing all the integers of the original array, which is what you need.
The reason for this behavior is the Arrays.asList expects one or more Objects as its input. If you pass an array of Objects (such as Integer[]), it is equivalent to passing multiple Objects. If, however, you pass an array of primitives (such as int[]), the only Object in your input is the array itself, so Arrays.asList() creates a list whose only element is that array.
Related
How can I add an element to an array while expanding the length of the array by one unit without using ArrayList? I'm a student, and it's forbidden for the assignment.
I have written a method that does it (sort of). It increments the array length every time its called but it only saves the last input parameter tot the very last element (every other element is made null when I create the new array with new length). The method is called in my constructor that makes an instance of an object from every line scanned in a text file, and I am supposed to add this line to an instance array.
You can't.
You can only create a new array which is longer than the old one. Other references of your program, already having a reference to the old array, are not affected and keep the old sized array.
I'm having an issue where I'm trying to populate an Array with values from a list, then replace the old values with the new ones upon each call of the method. The code below works once, then the next attempt it gives no errors until the new array variable is used , as the array which should have been populated with list data just is full of null values. If anyone has any suggestions much appreciated.
Integer[] stockFF2 =new Integer[ordersBFList.size()];
Integer[] ordersFF2 =new Integer[stockBFList.size()];
stockFFList.toArray(stockFF2);
ordersFFList.toArray(ordersFF2);
I think you have got the sizes wrong (orderFF2 and stockFF2 are using the sizes of each other's lists). I suspect one of the arrays is populated properly - one with the larger array - while the other allocates and returns a new array with the elements you want keeping the passed in array as it was because it is too short.
The toArray() method makes a fresh array and copies the contents of the list into it.
Try
Integer[] stockFF2 = stockBFList.toArray();
Integer[] ordersFF2 = ordersBFList.toArray();
If you want to reuse these arrays (seldom worthwhile), then replace their values with:
stockFF2 = stockBFList.toArray(stockFF2);
ordersFF2 = ordersBFList.toArray(ordersFF2);
It's unsafe to ignore the return value. If the source Collections get larger, the return value is another fresh array.
I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List.
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size().
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();
I've been reading up on it, but every question I've found has asked for slightly different things, such as only wanting a single letter for their array, or in a different language (I'm new and only learning java at the moment), so here I am.
I want to set up an array that uses the user's input for their names.
What I have so far is this, I'm assuming this is the declaration line, where later I use an input line to define a value within the array (which I also am unsure how to do)
String[] array = {"name"};
But I don't know how to for example print.out the object or keep up with which name will be what value. I appreciate your time taken to teach me!
EDIT for further clarification. I'm trying to write up a small app that asks the user for numerous names, addresses, and phone numbers (Type name -> Type name's address -> type name's phone number, ask if they want to add another person, if yes then go back to asking for another name)
I am unsure how to set up a String array or how to use it throughout. However, thanks to your input and coming back after some fresh air, I have a better idea how to word it for google. Thank you guys for your help, even if it was just to gesture a better articulated question.
An array is a sequence of values. You have created an array of Strings that is one String long. To access the value at a specific of an array, use array subscript notation: the name of the array followed by a pair of square brackets ([]) with the index in between them.
String[] anArrayOfStrings = {"string0", "string1", "string2"};
anArrayOfStrings[0]; //the first element
System.out.println(anArrayOfStrings[1]); //print the second element
anArrayOfStrings[2] = "new string value"; //assign the third element to a new value
if (anArrayOfStrings[0].equals("string0") //evaluate the first element and call a method
{
//this block will execute anArrayOfStrings[0] is "string0"
}
anArrayOfStrings[3]; //error, index out of bounds
Simply declaring the array would be
String[] names;
In your code you both declare and assign it in the same line by using an initializer list.
To assign individual elements, use the [] notation. Note that once you initialized you list to be only one String long, it cannot become longer than without be re-assigned. To declare an array of any size, you can use:
String[] arrayWithInitialSize = new String[5]; //holds five strings, each null to begin with
I have few files which I put in array.
I shuffle the files so that it can be displayed in random order.
How to know that array index 0 is actually image1.txt or image2.txt or image3.txt?
Thanks in advance.
String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
Collections.shuffle(files);
I'm not sure what you are trying to do.
To access the first element of the shuffled list, use files.get(0).
If you want to know where each element is gone, I suggest you take another approach to it. Create a list of integers from 0 to a.length() - 1, inclusive and shuffle that list. Then manually permute the array a to a new collection.
INCORRECT - see explanation
Note: Arrays.asList() will create a NEW list with the contents of the passed array. The original array will not be modified at all when you use Collections.shuffle().
Explanation
Peter has correctly pointed our that Arrays.asList() does NOT make a copy. The returned list is "write-through" back to the original array. Shuffling the list will shuffle the contents of the original array. Also worth noting that the list is immutable (new elements cannot be added) but typically I find that the use of Arrays.asList() involves immutable lists anyway.
files.get(0); // get the first elements in shuffled list, random
// as greg said
int index = files.indexOf(a[0]); // find out where "image1.txt" is in the list
files.get(index); // get "image1.txt" back from the list