equivalent of vector<T> in Java [duplicate] - java

This question already has answers here:
Equivalent of std::vector in Java?
(9 answers)
Closed 9 years ago.
I'm using Java programming language.
C++ has vector<T> and I need the equivalent vector in Java.
I want to convert this code to Java.
Vector<T> a[Maxn]; // Example: string, int, myclass, myvar, ...
int n;
cin >> n;
for(int i=0; i<n; i++)
{
T x, y;
cin >> x >> y;
x--, y--;
v[x].push_back(y);
}

You are probably looking for ArrayList
Resizable-array implementation of the List interface. Implements all
optional list operations, and permits all elements, including null. In
addition to implementing the List interface, this class provides
methods to manipulate the size of the array that is used internally to
store the list.
Something like this:
ArrayList ar = new ArrayList<String>();
ar.add("abc");

You can use List<T>, Java has many better ways, take it easy!
you could Search it...

Have a look at java.util.List. There are many concrete implementations of list including java.util.ArrayList
Here is an example using ArrayList
Note Java Collections e.g. List<T> make use of generics. Below I am using a list of String
List<String> list = new ArrayList<String>();
list.add("some string");

I'm pretty sure that this is the class you are looking for:
java.util.List

If you want something analogous to C++'s std::vector, I would start by looking at the various classes that implement the List interface (http://docs.oracle.com/javase/7/docs/api/java/util/List.html).
Probably the most commonly-used List is ArrayList, which has all the normal operations you would expect - add, get, size, iterator, etc.
Alternatively there is LinkedList, which is useful in its own way, depending on what exactly you're trying to achieve.

EDIT: I do not advocate using java.util.Vector<E>, but since you are coming from a C background, it might give you a warm fuzzy to use the same name. However, you should note (from the Java API)
Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
So it's best to use some other implementation of java.util.List<E> -- most common to use java.util.ArrayList<E>

Related

Interface with concrete classes [duplicate]

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.

converting an integer into an iterable object to facilitate code reuse

I am creating a datatype that needs to support two methods:
length(int v, int w)
length(Iterable<Integer> v, Iterable<Integer> w)
the first one is a special case of the second method and I want to reuse the code. How do I efficiently convert an integer into an Iterable object?
So far, I used an ArrayList.
ArrayList<Integer> a = new ArrayList<Integer>(); a.add(v);
ArrayList<Integer> b = new ArrayList<Integer>(); b.add(w);
return length(a,b);
Thanks.
Why do you want to use the same method? I think it is better use two differents methods, this is the purpose of overloading.
When you use the Iterable you have to use autoboxing of java to create Integer and then create the ArrayList, it is worse than use two differents methods, also to let the code more simple to read.
But if you want to use only Iterable I would use this code (to use the less possible code) or #sisyphus code:
length(Arrays.asList(1), Arrays.asList(2));
Merging varargs with ArrayList conversion allows you to create an ArrayList in a cool way.
Here you can see the working code:
code Iterable

Difference of List and ArrayList in declaration? [duplicate]

This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
List versus ArrayList as reference type?
(3 answers)
Closed 9 years ago.
Is there a difference between these two? If so, what is it?
List<Integer> x = new ArrayList<Integer>();
and
ArrayList<Integer> x = new ArrayList<Integer>();
The first declaration lets you program to interface. It ensures that later on you can safely replace ArrayList with, say, LinkedList, and the rest of code is going to compile.
The second declaration lets you program to the class, so you could potentially use methods of ArrayList which do not implement the List interface. For example, you can call ensureCapacity() on the list declared as ArrayList, but not on a list declared as List. Although generally programming to interface should be preferred, there is nothing wrong with doing it if you must call class-specific methods: for example, ability to call ensureCapacity() could save some unnecessary reallocations if you know the new target size of your list.
The former is preferred. It allows changing the implementation without changing code that depends on the field.
In Effective Java, Joshua Bloch says:
If appropriate interface types exist, then parameters, return values, variables and fields should all be declared using interface types.
...
If you get into the habit of using interfaces as types, your program will be much more flexible.
If you code to interfaces then you can change the implementation without much hassle
List<Integer> x = new ArrayList<Integer>();
you can make x now point to a LinkedList or any other implementation of List with only one line of code. If you need a specific method that is in ArrayList then having ArrayList on the left hand side is perfectly acceptable. 99 times out of 100 thought you wont so List is preferred
With ArrayList you can specify an intitalsize and so ArrayList has trimToSize() method to trim its size to the current size.With List<Integer> you won't be able to trim the size unless you cast it back to ArrayList

Java data structures (simple question)

Say I want to work with a linked list in java. I thought that the best way to create one is by:
List list = new LinkedList();
But I noticed that this way I can only use methods on the list that are generic. I assume that the implementation is different among the different data structures.
So if I want to use the specific methods for linked list, I have to create the list by:
LinkedList list = new LinkedList();
What's the main reason for that?
Tnanks.
List is an interface that abstracts the underlying list implementation. It is also implemented by e.g. ArrayList.
However, if you specifically want a LinkedList, there is nothing wrong with writing LinkedList list. In fact, if you just pass it around as a list, people may (not knowing the implementation) unknowingly write algorithms like:
for(int i = 0; i < list.size(); i++)
{
// list.get(i) or list.set(i, obj)
}
which are linear on a random access list (e.g. ArrayList) but quadratic on a LinkedList (it would be preferable to use a iterator or list iterator). Java provides the RandomAccess marker interface so you can distinguish.
Of course, you can call these methods on a reference of type LinkedList too, but people should be more likely to consider the cost.
As a note, in .NET LinkedList does not implement IList for this reason.
The first idiom allows you to change the runtime type that list points to without modifying any client code that uses it.
What methods in LinkedList do you think you need that aren't in List? You can always cast for those.
But the whole idea behind interfaces is to shield clients from how the interface is implemented.
If you really need a LinkedList, so be it. But I prefer the first idiom, because most of the time I really just need List methods.
Every LinkedList is a List, too. That also means that you can do everything with a LinkedList that you can do with a List and that you can store a LinkedList as List. However, when you store it as List, you can only call methods of the LinkedList that a List also has.
By the way: This is not Generics. Generics are like this:
LinkedList<String> list = new LinkedList<String>();
List list = getSomeList();
Here you're saying that it's a list. You have no idea whether or not it's a LinkedList or an ArrayList or whatever. It is an abstract thing (I assume you mean "abstract" by the word "generic", since generics are a different thing entirely). Thus you can't treat it like it's an LinkedList -- you have to treat it like it's a List (which it is).
The fact that "you know" that it's a LinkedList is all well and good, and you can safely cast if you need to do it. But it might help to tell the compiler that it's a LinkedList, by declaring it as so, if it's always going to act as a LinkedList.

What function can be used to sort a Vector?

I cant find any sorting function in the java API for vectors.
Collections.sort is only for List<T> and not for Vector<T>.
I don't want to write my own sorting function because I think java should implement this.
I'm looking for something like:
class ClassName implements Comparator<ClassName> ..
ClassName cn = ..;
sort(cn);
As per the API docs, Vector just implements List, so I don't forsee problems. Maybe your confusion was caused because you declared Vector according the old Java 1.0 style:
Vector vector = new Vector();
instead of the declaring it aginst the interface (which is considered good practice):
List list = new Vector();
You can thus just make use of Collections#sort() to sort a collection, Comparable to define the default ordering behaviour and/or Comparator to define an external controllable ordering behaviour.
Here's a Sun tutorial about ordering objects.
Here's another SO answer with complete code examples.
That said, why are you still sticking to the legacy Vector class? If you can, just replace by the improved ArrayList which was been designed as replacement of Vector more than a decade ago.
Vector implements List, so Collections.sort would work.
According to the Java API Specification for the Vector class, it implements the List interface which is needed to use the Collections.sort method.
Also, as a note, for most uses the Vector class could be replaced by using one of the List implementations in the Java Collections Framework, such as ArrayList. The Vector class is synchronized, so unless there is a real need for synchronized access one should use one of the other List implementations.
Vector is a List
Collections.sort(nameOfTheVectorToBeSorted); try this on your vector, that will get sorted.
Don't forget to add implements Comparable<> in your class:
public class XXXX
implements Comparable<XXXX> {
}
And to redefine compareTo() in your class of the object type stored in your vector.
I got this problem as well, Eclipse IDE was telling me that Collection.sort() was for List<T> only. Couldn't make it work until I did what I just said.
Collections.sort(vector_name)
It'll sort the vector in place, so you don't need to assign the result of the above command back to the vector.
This works because Vectors are implementations of Lists.

Categories

Resources