链表.java中this()的用途是什么 [英] Whats the use of this() in linkedlist.java

查看:63
本文介绍了链表.java中this()的用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看着Linkedlist.java,我观察到重载的构造函数,其中一个包含一个空的this().通常,我已经使用默认参数看到了这一点.没有参数的this()有什么用?

 /***构造一个空列表.*/公共LinkedList(){}/***构造一个包含指定元素的列表*集合,按集合的返回顺序*迭代器.** @param c要将其元素放入此列表的集合* @throws NullPointerException如果指定的集合为null*/公共LinkedList(Collection< ;?扩展E> c){这();addAll(c);} 

解决方案

这称为构造函数链接.它是一种机制,使对象可以从其最通用的超类( Object )的构造函数开始进行初始化,然后向下移动至更具体的对象(每个级别将新对象初始化为其有效状态)课程,然后再继续下一个课程.

构造函数可以选择在当前类(由this表示)或父类(由super表示)的哪个其他构造函数将在运行之前调用.除非指定了其他内容(或者如果父类中的无参数构造函数不可见),则默认的链接选项是(隐式) super().

在您的情况下, this()意味着构造函数 LinkedList(Collection< ;?扩展E> c)将首先调用 LinkedList()构造函数.在您的代码段中,是无操作的,它的存在确保了无参数构造函数的初始化策略中的任何更改也将被另一对象采用.因此,这使得更改类的初始化逻辑的错误几率降低了.

Looking at Linkedlist.java, I observe overloaded constructors, one of which contains an empty this(). Generally I have seen this with default params. Whats the use of this() with no params in it ?

 /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

解决方案

This is called constructor chaining. It is the mechanism that enables objects to be initialized starting from the constructor of their most general superclass (Object) and moving down to the more specific ones (each level initializing the new object to a valid state for its class before moving on to the next).

A constructor can choose which other constructor of the current class (denoted by this) or the parent class (denoted by super) will be invoked before this one is run. The default chaining option is (implicitly) super(), unless something else is specified (or if a parameterless constructor in the parent class is not visible).

In your case, this() means that the constructor LinkedList(Collection<? extends E> c) will first call the LinkedList() constructor. While in your snippet it is a no-op, its presence ensures that any changes in the initialization strategy of the parameterless constructor will be also adopted by the other one. So it makes changing the initialization logic of the class a little less error prone.

这篇关于链表.java中this()的用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆