It's a boring article, but it's ideal for beginners to study because it uses type parameters in short code and uses super and this properly, and it also shows the value of the inheritance function peculiar to object-oriented programming. It is a content that you can experience with.
In java's ʻArrayList , you can store ʻelement
as the ʻindex th element using the method
set (int index, T element) . However, if you do this when the number of elements is ʻindex
or less, java.lang.IndexOutOfBoundsException
will occur.
It's sober and troublesome.
I wrote a child class ʻAL of ʻArrayList <T>
.
Decide in advance "what to fill when the number of elements is insufficient"
When the number of elements is actually insufficient, fill it.
The code looks like this:
AL.java
class AL<T> extends java.util.ArrayList<T>
{
private T filler = null;//※
void fillBy(T filler){this.filler = filler;}
//If it seems to be set in a place that does not exist, fill it with a filler
public T set(int index, T element)
{
if(filler!=null) while(this.size() <= index) this.add(filler);
return super.set(index, element);
}
//The same is true for get
public T get(int index)
{
if(filler!=null) while(this.size() <= index) this.add(filler);
return super.get(index);
}
}
filler
by default, set the initializer of the child class.
{this.filler = (default filler);}
Must be. In this case, the access modifier should be protected instead of private.sample.
Main.java
class Main
{
public static void main(String...args)
{
AL<String> al = new AL<>();
al.add("indigenous");
//al.fillBy("I filled.");
al.set(3, "immigration");
for(String s : al)
System.out.println(s);
}
}
If this is left as it is, an exception will occur and it will not work as before.
However, when the commented out fillby
method is enabled, no exception is raised and the following is displayed.
indigenous
I filled.
I filled.
immigration
Recommended Posts