What would be the best way to store and read a really long string, with each entry is an index for another array?
Right now I have this
String indices="1,4,6,19,22,54,....."
The string has up to hundred of thousand entries, so I think maybe I could use a data structure like Linked List. Does anyone know if it would be faster to use one?
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
you need to declare arraylist of type string.Then add to it.
It would depend on what you'll do with the string (the indices) and the corresponding arrays. Also, it will depend on how you're gonna access them.
I'd suggest you first read an overview about the data structures implemented in java, specially in the Collections Framework.
We could give some suggestions, but you'd have to provide us more information, specially those I mentioned in the beginning (what you want, how this data will be stored and accessed, and so on).
For example, if you need to have a fast access to the indexed data, maybe a string isn't even the best approach. Maybe a map would be better. The indexes could be the keys and the indexed arrays could be the values of the map, for example. But this is just a void example, I strongly suggest you give us more information.
I really like using the ArrayList class, which if your comfortable using arrays, ArrayList or any member of the Collections Framework. Would work really well. For what your trying to do.
ArrayList<String> indices = new ArrayList<String>();
indices.add("");
I have similar hunch in my mind , in which I want to like 1k number of strings and parse them (searching purpose to know it contain item or not).
Hence I found instead of using java collection framework - map or set or list
if I store data simply in array and start parsing data using for-loop, it is faster.
You visit this link and see actual output which we calculated in micro seconds.
https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/
So using simple brute force is winner in case of unsorted array
(normally we have).
But arrays.BinarySearch() is winner if array is sorted.
Related
Is there any way I can input data into any array list without actually doing the following in each place in the code where I need to insert data?
ArrayList<dataType> kwh = new ArrayList<dataType>();
arrayListVariable.add(data);
arrayListVariable.add(moreData);
arrayListVariable.add(evenMoreData);
As of right now, this seems to be very time consuming if I need to put in quite a bit of data into the array list. Is there a simpler/more concise way of doing this?
You could use like:
ArrayList<dataType> kwh = new ArrayList<dataType>(Arrays.asList(data, moreData, evenMoreData));
Alternatively, you could use Guava's Lists class.
To add new elements:
List<Integer> ints = Lists.newArrayList(1, 2, 3);
However, this one is not fixed size. You can add new elements just by calling ints.add() afterwards.
That depends upon what you mean by "faster".
If you're talking about how fast the program runs, the add() method runs in constant time. You're not going to get much better than that unless you use an actual array. You're using an ArrayList, though, so I'm going to assume you're willing to trade away some of the speed/space optimization for the flexibility.
If you mean "How can I add a lot of data to a list without a lot of typing", then answer is this: It depends upon what you're doing.
If you're reading from a file, create a method that splits files by whatever separator is used between data elements. Loop through these items and add them to your ArrayList.
If you're doing something else, then you're going to have to find a way to loop through the data . Once you get it into an array, the rest is pretty simple.
I am writing a program that will be heavily reliant on ... something ... that stores data like an array where I am able to access any point of the data at any given time as I can in an array.
I know that the java library has an Array class that I could use or I could use a raw array[].
I expect that using the Array type is a bit easier to code, but I expect that it is slightly less efficient as well.
My question is, which is better to use between these two, and is there a better way to accomplish the same result?
Actually Array would be of no help -- it's not what you think it is. The class java.util.ArrayList, on the other hand, is. In general, if you can program with collection classes like ArrayList, do so -- you'll more easily arrive at correct, flexible software that's easier to read, too. And that "if" applies almost all the time; raw arrays are something you use as a last resort or, more often, when a method you want to call requires one as an argument.
The Array class is used for Java reflection and is very, very, rarely used.
If you want to store data in an array, use plain old arrays, indicated with [], or as Gabe's comment on the question suggests, java.util.ArrayList. ArrayList is, as your comment suggests easier to code (when it comes to adding and removing elements!!) but yes, is slightly less efficient. For variable-size collections, ArrayList is all but required.
My question is, which is better to use between these two, and is there a better way to accomplish the same result?
It depends on what you are trying to achieve:
If the number of elements in the array is known ahead of time, then an array type is a good fit. If not, a List type is (at least) more convenient to use.
The List interface offers a number of methods such as contains, insert, remove and so on that can save you coding ... if you need to do that sort of thing.
If properly used, an array type will use less space. The difference is particularly significant for arrays of primitive types where using a List means that the elements need to be represented using wrapper types (e.g. byte becomes Byte).
The Array class is not useful in this context, and neither is the Arrays class. The choice is between ArrayList (or some other List implementation class) and primitive arrays.
In terms of ease of use, the Array class is a lot easier to code.
The array[] is quite a problem in terms of the case that you need to know
the size of the list of objects beforehand.
Instead, you could use a HashMap. It is very efficient in search as well as sorting as
the entire process is carried out in terms of key values.
You could declare a HashMap as:
HashMap<String, Object> map = new HashMap<String, Object>();
For the Object you can use your class, and for key use the value which needs to be unique.
I was wondering if I could create an array without having to enter a value. I don't fully understand how they work, but I'm doing an inventory program and want my array to be set up in a way that the user can enter products and their related variables until they are done, then it needs to use a method to calculate the total cost for all the products. What would be the best way to do that?
Use an ArrayList.
This will allow you to create a dynamic array.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
Here is an example/overview:
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Yes, you can do this. Instead of using a primitive type array, for example new int[10], use something like the Vector class, or perhaps ArrayList (checkout API docs for the differences). Using an ArrayList looks like this:
ArrayList myList = new ArrayList();
myList.add("Item 1");
myList.add("Item 2");
myList.add("Item 3");
// ... etc
In other words, it grows dynamically as you add things to it.
As Orbit pointed out, use ArrayList or Vector for your data storage requirements, they don't need specific size to be assigned while declaration.
You should get familiar with the Java Collections Framework, which includes ArrayList as others have pointed out. It's good to know what other collection objects are available as one might better fit your needs than another for certain requirements. For instance, if you want to make sure your "list" contains no duplicate elements a HashSet might be the answer.
http://download.oracle.com/javase/tutorial/collections/index.html
The other answers already told how to do it right. For completeness, in Java every array has a fixed size (length) which is determined at creation and never changes. (An array also has a component type, which never changes.)
So, you'll have to create a new (bigger) array when your old array is full, and copy the old content over. Luckily, the ArrayList class does that for you when its internal backing array is full, so you can concentrate on the actual business task at hand.
I have this code:
newArray = new String[][]{{"Me","123"},{"You","321"},{"He","221"}};
And I want to do this dynamically.
Add more elements, things like it.
How do I do this?
PS: Without using Vector, just using String[][];
You can't change the size of an array. You have to create a new array and copy all content from the old array to the new array.
That's why it's much easier to use the java collection classes like ArrayList, HashSet, ...
You can't change the size of arrays. I think you have some options:
use a List<List<String>> to store a list of lists of strings
use a Map<String,String> if you're storing a key/value pair
Vector tends not to be used these days, btw. A Vector is synchronised on each method call, and thus there's a performance hit (negligible nowadays with modern VMs)
Java does not have the facility to resize arrays like some other languages.
But
You would not see a difference between a String array and a ArrayList<String> (javadoc) unless you are specifically required to do so (like in homework)
There are ways where you can declare a enormous array so that you dont run out of space but I would strongly recommend ArrayList for if you need dynamic changes to the size. And ArrayList provides some possibilities that are not (directly) possible with an array, as a bonus.
You can get away with using arrays if it's possible to calculate the size of arrays before using them. In your example, it seems that we need to know the size of the first array only. So you could impose some limit of how many records could be saved, or you could query user to know how many records it needs to save or something similar.
But again, it's easier to use Collections.
I have a short (12 elements) LinkedList of short strings (7 characters each).
I need to search through this list both by index and by content (i.e. search a particular string and get its index in the list).
I thought about making a copy of the LinkedList as an array at runtime (just once, since the LinkedList is a static member of my class), so I can access the strings by index more quickly.
Given that the LinkedList is never changed at runtime, is this bad programming practice or is this an idea worth considering?
IMPORTANT EDIT: the array can't be sorted, I need it to map specific strings to specific numbers.
Instead of a LinkedList just use an ArrayList - you can look up fast based on an index, and you can easily search through it.
What problem are you trying to solve here? Are you worried that accessing elements by index is too slow in LinkedList? If so, you might want to use ArrayList instead.
But for a 12-element list, the improvement probably won't make any measurable difference. Unless this is something you're accessing several hundred times a second, I wouldn't waste any time on trying to optimize it.
Another idea you might want to consider is using a Map:
Map someMap<int, String>
It's easy to search for values in a map by both key and value.
Might also not be the best idea, but at least better then creating 2 lists with the same values =)
The question is, why are you using a LinkedList in the first place?
The main reason to choose a LinkedList over an array list is if you need to make a number of insertions/deletions in the middle of the List or if you don't know the exact size of the list and don't want to make a number of reallocations of the Array.
The main reason to choose an ArrayList over a LinkedList is if you need to have random access to each of the elements.
(There are other advantages/disadvantages to each, but those are probably the main ones that come to mind)
It looks like you do need random access to the list, so why did you pick a LinkedList over an ArrayList
I would say it depends on your intention and the effect it really has.
With only 12 elements it seems unlikely to me that converting the LinkedList to an array has an impact on performance. So it could make the code unnecessarily (slightly) harder to understand for other people. From this point of view it could be considered a non optimal programming style.
If the number of elements increases, i.g. you're need to pre-process some data which would require a dynamic data structure. And for later use an indexed lookup performs much better, this wouldn't be a bad programming style, rather a required improvement.
Given that you know the exact amount of elements you are going to be using why not use an array from the start?
string[] myArray = new string[7];
// Add your data
Sort(myArray); // Sort your strings
int value = binarySearch(myArray, "key"); // Search your array
Or since you cant sort the array you could just make a linear search method
public int Search(string[] array, string key)
{
for(int i = 0; i < array.legnth(); i++)
{
if(array[i] == key)
return i;
}
return -1;
}
Edit: After re-loading the page and reading peoples responses I agree that ArrayList should be exactly what you need.