So I want to write a programm, that can manage workouts.I have a class "Excersise" and I will create many Objects from this class. Im wondering how I should handle all these Objects. Till now I had an ArrayList with all Excersises in it but when I want to add an Excersise to a workout, I would have to do it like this: workout.add(excerises.get(index)) meaning I would have to know the index for every excerises. Also Im wondering how good the performany of ArrayLists are. Should I consider to use another data structure?
If you have constant pool of Excersises, and you only need to access them by index, then you can use array instead:
Excersise[] excersises = new Excersise[EXCERSIZE_SIZE];
//fill excersises
//use excersises
workout.add(excersises[index]);
ArrayList is designed to have fast access to element by index, and it is using array underneath, but it has range check inside it's get method. On the other hand ArrayList provide a bunch of useful methods, in case if you need any of them. The other thing is that if you would like to hold a lot of objects in it it might be wise to create it with some capacity, which you expect, knowing of how many objects you will add to this ArrayList, for example if you expect 1000 objects then you can do:
List<Excersise> excersises = new ArrayList(1000);
In that way you'll omit recreating of arrays inside ArrayList.add method when array inside ArrayList will not be able to store provided value (HashMap also has constructor HashMap(int initialCapacity)).
If you would like to access to excersise for example by it's symbolic name, let's say "push ups", then you can use HashMap:
Map<String, Excersise> excersiseByName = new HashMap<>();
//fill excersises
workout.add(excersiseByName.get("push ups"));
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
If we consider two implementations below, what's the actual use of the first one?
List<String> a= new ArrayList<String>();
ArrayList<String> b= new ArrayList<String>();
From what I have read in the posts, the first implementation helps in avoiding breaking change like we can change the implementation again as
a=new TreeList<String>();
But I don't understand whats the actual use of changing the implementation with treelist as we can use only the List interface methods?
But I don't understand whats the actual use of changing the implementation with treelist as we can use only the List interface methods?
Different implementations of interface List have different performance characteristics for different operations. Which implementation of List you should choose is not arbitrary - different implementations are more efficient for different purposes.
For example, inserting an element somewhere in the middle is expensive on an ArrayList, but cheap on a LinkedList, because of the way the implementations work. Likewise, accessing an element by index is cheap on an ArrayList, but expensive on a LinkedList.
It may happen that when you started writing your program, you used an ArrayList without thinking about it too much, but later you discover that a LinkedList would be more efficient.
When you've programmed against the interface List instead of a specific implementation, it's very easy to change from ArrayList to LinkedList - to the rest of the program, it still looks like a List, so you'd only have to change one line.
Lets say that you have decided to develop a more efficient List implementation of your own. Perhaps one that has better memory management internally, or may be a faster set method (insertion) implementation. You can just implement the List interface and rest of your code will continue to work without any change, except this one line. You can also extend ArrayList and write your own code.
//Old code
List<String> a = new ArrayList<String>();
a.set(0, "Test");
//New code
List<String> a = new MyCustomisedList<String>();
//Same code, but your optimized set logic. May be faster...
a.set(0, "Test");
A TreeList doesn't exist, so lets use a PersistentList as an example.
Lets say you have an #Entity that you want to save to a database:
public class MyMagicEntity {
#OneToMany
List<MyChildEntity> children;
public void setChildren(final List<MyChildEntity> children) {
this.children = children;
}
}
Now, when you create MyMagicEntity then you would do something like
final MyMagicEntity mme = new MyMagicEntity();
final List<MyChildEntity> children = new ArrayList<>();
children.add(new MyChildEntity("one"));
children.add(new MyChildEntity("two"));
children.add(new MyChildEntity("three"));
mme.setChildren(children);
//save to DB
So you created an ArrayList that you passed into your MyMagicEntity, which assigns it to the List - it doesn't care that the underlying implementation is as long as it's a List.
Now, later you do:
final MyMagicEntity mme = //load from DB
final List<Children> children = mme.getChildren();
So, what is children? Well, if we are using JPA and Hibernate it is actually a PersistentList, not an ArrayList.
As we access the members of children, Hibernate will go and pull them from the database. This List is still a List - your program doesn't have to know any of this.
Could you do this without using the List interface? No! Because:
you cannot create a PersistentList
Hibernate cannot create an ArrayList
Whilst this is an extreme example, where the underlying behaviour of the List is completely different, this applies in all sorts of other situations.
For example:
ArrayList and LinkedList have different performance characteristics, you may want to switch
Guava has an ImmutableList which you may want to use
Collections.unmodifyableList also implements List, which you may want to use
You could conceivably have a List backed by a file
The basic idea is that List defines what any list must be able to do, but not how it is done.
Here List is an Interface which contains all common operation method can perform with an List.
List Interface is parent for ArrayList , LinkedList and many more class. So, It can hold all these type of Object reference.
All these List method have different (or own type) Implementation with different class. So, whatever method you use will automatically apply according to override method definition of Object belong to the class.
List<String> a= new ArrayList<String>();
ArrayList<String> b= new ArrayList<String>();
Now , In Your case you can declare both ways is alright. but suppose a Scenario like this.
You are calling some services and you know that return any List Type (not specific) of Object. It may be a LinkedList or ArrayList or any other type of List.
at that time whatever response you get You can easily hold those responses in a List Type of Reference Variable.
and after gathering the result you can differentiate further of Object Type.
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.
I have an very large array of objects where objects are constantly added and every object is dynamic and contains different parameters that define it (getParam1() etc..).
I need a data type that allows me to point directly to an object in the array that contains a specific parameter without having to index through the entire array every time that I require a specific object.
Does any datatype provide this functionality in java or would I have to create my own? And in that case how would I do this?
Thanks.
You could maintain one map per parameter and update each one when the parameter changes. If you don't have control over either the mutating, or the mutable class, then there's not much else you can do other than linearly search through your objects.
I have an very large array of objects where objects are constantly added and every object is dynamic and contains different parameters that define it (getParam1() etc..).
An array is an static structure. If you're going to constantly add elements to it you should reconsider using a dynamic collection such as a List, a Set or a Map. If you're not modifying the length of the array and you're just updating the different objects on it, you're ok. Still, you are going to have to keep track (an index, amount of objects, etc.) of the array's current status, because you will need to know where to put your objects.
I need a data type that allows me to point directly to an object in the array that contains a specific parameter without having to index through the entire array every time that I require a specific object.
This will require some middle logic one way or another. If you point to an object that has certain parameter what happens if more than one object has it? You have to define which one is the correct one. On the other hand, if you point to the parameter you still need to know the related object.
I'd say that rather than using an array you should try with a Map with entries where the key is the parameter and the value is a Set, containing the different objects related to that parameter.
A Map is sufficient if you only map a parameter to one object, but I'll cover a more complex situation, just in case.
Please note that an object can be present in multiple Sets, because two parameters would require for it to be mapped twice to allow it to be found.
I've looked into maps but it's not really ideal when it comes to my objects.
I don't know your current context and how do you identify your objects. Should you have an ID or any sort of unique identity assertion, you can turn the Map of Sets to a Map or Maps where you can obtain a Map containing objects associated to a certain function and then obtain a particular object through that ID.
Finally, if nothing suffices, you should create a structure that covers your needs. Still, for instant access, you're better off using a Map or a really well-oiled array.
Use a Map instead of an array:
Map<String, MyObject> map = new HashMap<String, MyObject>();
MyObject o;
String someId = o.getId(); // use some identifying id for your objec
map.put(someid, o); // do this for all your objects
then when you need to retrieve one:
MyObject o = map.get(someId);
If you need all the objects (possible, but unlikely):
List<MyObject> objects = map.getValues();
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.