Collection col = new LinkedList();
Is there a way to call col.addFirst ?
Yes, if you cast to LinkedList:
((LinkedList) col).addFirst(..)
But this is discouraged, because you don't always know the concrete type of the collection. You can check with instanceof, but that is not good object oriented code. If you really require a LinkedList, require a LinkedList (rather than Collection)
If you declare a variable as Collection, this means that you normally plan to consider this variable, in the rest of your program, as a simple Collection, and not as a linked list. The methods offered by the Collection interface should be sufficient for the rest of your program using this variable.
If you need access to a specific method only present in the LinkedList class, then the variable should be a declared as LinkedList.
I am not sure why you need to use Collection in this case, however you can still "program to an interface and not to an implementation" if you use the interface java.util.Deque which, by chance, also extends java.util.Collection
Deque<String> deque = new LinkedList<String>();
deque.addFirst("Hello");
Collection<String> collection = deque;
If you use List instead of Collection, then the .add() method is available. Add at index 0 to put it in on the first position.
list.add(0, object)
Related
List is an interface.
List<String> list=new ArrayList<String>();
Here, lets say we are creating a reference variable of list interface and assigning it to the ArrayList object which implemets List interface.
Lets say if we want to get the size of the list. We will use list.size() which will internally invoke the size() method of ArrayList object using Runtime Polymorphism.
Simply here what I mean to say is the methods of List is implemented in ArrayList class thats why we are able to use it.
Question is,
How I am able to use size() and how the size method is being implemented in what Class ?
List<WebElement> noOfRows=driver.findElements(By.xpath(".//*[#id='leftcontainer']//tbody/tr"));
List<WebElement> noOfCol=driver.findElements(By.xpath(".//*/tr/th"));
int rowSize=noOfRows.size();
int colSize=noOfCol.size();
I hope you guys are getting my point.
When I say List<String> list= new ArrayList<String>();
That means I am going to use ArrayList methods as runtime polymorphism.
But what in this case...
driver.get("https://money.rediff.com/gainers/bse/daily/groupa?src=gain_lose");
List<WebElement> noOfRows=driver.findElements(By.xpath(".//*[#id='leftcontainer']//tbody/tr"));
List<WebElement> noOfCol=driver.findElements(By.xpath(".//*/tr/th"));
int rowSize=noOfRows.size();//How I am able to use method of a List interface
int colSize=noOfCol.size();
I am able to run the program and do everything but just want to clear the concept here . Seems like I am confused on a minor issue but want this confusion to be gone. Thankyou in advance
A variable in Java can have a type List, but it is not possible to instantiate the List interface, that is, to create an object of type List in memory. The objects in memory are of some other type that implements the List interface.
The object returned from findElements implements the interface List, but the actual class of that object is unknown to the compiler. You can query it at runtime, by using the getClass method, but that is usually not necessary because you can treat it as a List without having to know exactly what kind of List it is.
When you call size on the List returned by findElement, the JVM selects the correct size implementation to use based on the actual type of the object. So if it just happens to be an ArrayList then you'll get ArrayList.size, etc. Often the type of List returned from a method like this isn't one of the usual types from java.util but some custom implementation that is tailored to the task at hand.
I am confused with a design problem in Java. It realized many abstract containers under the interface Collection and provides the method hasNext() and Next() along with class Iterator. What is the drawback if I put these methods directly under interface Collection and then overrides it in each subclass:
For example, I have already realized Next(); hasNext() method under class ArrayList. So what I wrote is
ArrayList ArrList=new ArrayList()
if(ArrList.hasNext())
new obj=ArrList.next();
}
returning the objects stored in ArrList.
So is it redundant to introduce Iterator class for the interface Collection? And what is the benefit to design ArrList.iterator(); if it's more covenient to set it up in interface?
Can I find any book to solve such oop-design problems(As the computer scientists described it)?
Thanks for your time.
The methods of the Iterator interface (next(), hasNext()) can't simply be added to the interface. An Iterator has a state which determines the next element that would be returned by the iterator.
If the Iterator methods were part of the Collection interface, you would need some additional method to reset this "built-in" iterator (in order to iterate again from the start of the Collection), and you would only have a single iterator for each Collection in any given time. A nested iteration as simple as the following snippet wouldn't be possible, since it requires two iterators :
List<Integer> list = ...
for (int i : list)
for (int j : list)
System.out.println(i+j);
Iterator stores a pointer to some element inside a collection. In case of ArrayList it is an index of the underlying array.
It allows you to say iterate over the collection in two separate threads simultaneously. If the pointer was a part of ArrayList, each of the threads would skip some of the elements.
An iterator is usually made to traversed once. In the Java collection library classes will fail if modifications are made to the underlying collection during a traversal of an iterator.
BTW, this question may be more appropriate for Programmers Stack Exchange which is dedicated to theoretical programming questions.
Let's assume for a moment that ArrayList did have hasNext and next methods, and so your code would compile. (You'd also need another method to tell the list you wanted to start over again.) That would mean that I could only have one iteration of the list active at a time, because the list itself contains the iteration state. That's just poor design; instead, we have the Iterator concept so that the state of the iteration is stored in the iterator, not the list, and we can have multiple iterators.
At the conceptual level: Collection represents a collection of objects. Adding methods for hasNext and next would turn it into a collection of objects along with another piece of state, a 'current object', as well as some concept of how to traverse the collection.
Since these are two separate ideas, it is best to divide them into separate structures that are implemented independently. In the case you speak of, that would be the Collection structure (which handles storage and structure for a collection of objects), and the Iterator structure (which handles position and traversal of some collection of objects).
I'm developing for Android and wondered, what are the main differences between an ArrayList and a List?
For the handling of objects collection in Java, Collection interface have been provided. This is available in java.util package.
"List" is an interface, which extends collection interface, provides some sort of extra methods than collection interface to work with collections. Where as "ArrayList" is the actual implementation of "List" interface.
The ArrayList class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second. If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class.Where as, if you use the second one, you are free to use all the methods available in the ArrayList.
EDIT:
In Java Applications development, when you are supposed to pass the collection framework objects as arguments to the methods, then it is better to go with
List tempList = new ArrayList();
somemethodcall(tempList);
because, in future due to performance constraints, if you are changing the implementation to use linkedlist or some other classes which implements List interface, instead of ArrayList, you can change at only one point (i.e) only the instantiation part. Else you will be supposed to change at all the areas, where ever, you have used the specific class implementation as method arguments.
user370305 gives an exact explanation. This may also help you understand the collections hierarchy in Java.
List is interface which ArrayList implements. If you are trying to create a method which needs a List of some kind but you are not bothered what implemntation is actually used then use List.
If you are actually instantiating a class then you have to pick some implementation of List one of which is ArrayList
List<String> l1 = new ArrayList<String>();
would be an example.
You can not instantiate an interface and so would get an error if you tried to do the following:
List<String> l2 = new List<String>();
There is a good article on wikipedia about that, where the arraylist is called "dynamic array".
If you are trying to optimize your application you should take a look at the table next to the article.
List is an interface and ArrayList is an implementation of the List interface. The ArrayList class has only a few methods in addition to the methods available in the List interface.
Have a look at the short article on JavaBeat - Difference Between List and ArrayList?
I know that the Collection framework allows for the creation of "views", that is lightweight "wrappers" for a Collection object.
What I am especially interested in is, given a List, to return a view for only a subset of elements matching some conditions.
Basically, what I want to emulate is the functionality of the subList() method, only not based on start and end indexes, but on some parameters of the elements.
The first approach I thought about was simply to create another List, go through the first List and check each element...
While this wouldn't be actually copy any MyObject but only their references, I would anyways create a new List object, with its overhead. Isn't that right?
Is there any lightweight method of doing what I need?
N.B. My original List is a really big collection...
Thank you all
You can do this easily in Java using the Guava collections (Collections2 has a filter method http://docs.guava-libraries.googlecode.com/git-history/v11.0.1/javadoc/index.html).
You can also do this in groovy using the findAll method, for example
myList.findAll { it.contains("aValue") }
Any of these methods will create a new collection under the hood. So they are just doing the work for you of iterating over the elements and checking them. The overhead of creating a new list is minimal (it's just instantiating one new object).
I would anyways create a new List object, with its overhead
I don't understand what your concern here. Looking at source of ArrayList class even subList(int fromIndex, int toIndex) method in List class creates a new inner class (which extends from List). That is essentially what you will be doing in your method i.e. create a new List instance and copy your matching element's reference into it. That custom method will be more or less will have same performance as subList method.
I am a beginner and I cannot understand the real effect of the Iterable interface.
Besides what Jeremy said, its main benefit is that it has its own bit of syntactic sugar: the enhanced for-loop. If you have, say, an Iterable<String>, you can do:
for (String str : myIterable) {
...
}
Nice and easy, isn't it? All the dirty work of creating the Iterator<String>, checking if it hasNext(), and calling str = getNext() is handled behind the scenes by the compiler.
And since most collections either implement Iterable or have a view that returns one (such as Map's keySet() or values()), this makes working with collections much easier.
The Iterable Javadoc gives a full list of classes that implement Iterable.
If you have a complicated data set, like a tree or a helical queue (yes, I just made that up), but you don't care how it's structured internally, you just want to get all elements one by one, you get it to return an iterator.
The complex object in question, be it a tree or a queue or a WombleBasket implements Iterable, and can return an iterator object that you can query using the Iterator methods.
That way, you can just ask it if it hasNext(), and if it does, you get the next() item, without worrying where to get it from the tree or wherever.
It returns an java.util.Iterator. It is mainly used to be able to use the implementing type in the enhanced for loop
List<Item> list = ...
for (Item i:list) {
// use i
}
Under the hood the compiler calls the list.iterator() and iterates it giving you the i inside the for loop.
An interface is at its heart a list of methods that a class should implement. The iterable interface is very simple -- there is only one method to implement: Iterator(). When a class implements the Iterable interface, it is telling other classes that you can get an Iterator object to use to iterate over (i.e., traverse) the data in the object.
Iterators basically allow for iteration over any Collection.
It's also what is required to use Java's for-each control statement.
The Iterable is defined as a generic type.
Iterable , where T type parameter represents the type of elements returned by the iterator.
An object that implements this interface allows it to be the target of the “foreach” statement. The for-each loop is used for iterating over arrays, collections.
read more -: https://examples.javacodegeeks.com/iterable-java-example-java-lang-iterable-interface/