简体   繁体   English

Java:从对象访问对象

[英]Java: Accessing objects from objects

I have an object to read data: 我有一个对象来读取数据:

DataReader dataReader = new DataReader();

And object to read: 和对象阅读:

Data data = new Data();

I can read data like so: 我可以这样读取数据:

dataReader.read(data);

Or I can pass data to dataReader constructor and read it within dataReader object. 或者,我可以将data传递给dataReader构造函数并在dataReader对象中读取它。

What is more efficient? 有什么更有效的?

And what is better in case read() method is implemented like this: 如果read()方法是这样实现的,那会更好:

public void read(Data data) {
        this.readString(data);
        this.readString(data);
    }

And method readString(Data data) : 和方法readString(Data data)

private void readString(Data data) {
        data.nextLine();
    }

Meaning, is it better to have one local data object and call its methods or pass it several times as methods argument when java passes object by value not reference ? 意思是,当java按值传递对象而不是引用时,最好有一个本地数据对象并调用其方法或将其作为方法参数多次传递 What works faster and consumes less memory? 什么能更快地工作并消耗更少的内存?

I am a little unsure as to what you mean for the second part of your question, but if you mean what I think then this should answer it. 对于您对问题的第二部分的意思,我有点不确定,但是如果您的意思是我的想法,那么这应该可以回答。

Calling the method in your constructor or your method is entirely dependent on usage. 在构造函数或方法中调用方法完全取决于用法。 For this case, are you going to be reading this data repeatedly? 对于这种情况,您是否要重复读取此数据? If you are, then creating one instance of a DataReader would be more efficient than creating one for each read, so using the method repeatedly on one instance would be more efficient. 如果是这样,那么创建DataReader一个实例将比为每个读取创建一个实例更有效,因此在一个实例上重复使用该方法会更高效。 If you are only using it once, then you don't want to have useless object instances hanging around in memory after they are done with, so creating a temporary instance and reading in the constructor would be more efficient. 如果只使用一次,则不要在处理完之后将无用的对象实例挂在内存中,因此创建一个临时实例并读取构造函数会更有效。

But as the comments say, these things are rarely concerns for optimisation and make little impact. 但是正如评论所说,这些事情很少是优化的考虑因素,几乎没有影响。 In theory it's interesting, but in practice don't worry about it unless you have to. 从理论上讲这很有趣,但是实际上除非您必须这样做,否则不必担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM