简体   繁体   English

x = y使x指向y吗?

[英]Does x=y makes x pointer to y?

I am sorry for such a stupid question, but I cant describe my problem any better. 对于这样一个愚蠢的问题,我感到抱歉,但是我无法更好地描述我的问题。 I have 2 classes: 我有2节课:

    //First Class
    public class VKtracks extends Fragment {

        RecyclerView list;
        SongListAdapter listAdapter;
        private ArrayList<song> songs = new ArrayList<>();
        MainActivity mainActivity;

        public VKtracks(){

        }

        @Override
        public void onActivityCreated (Bundle savedInstanceState){
            super.onActivityCreated(savedInstanceState);
            mainActivity = (MainActivity)getActivity();
            songs = mainActivity.songs;
            Iterator<song> itr = songs.iterator();
            while (itr.hasNext()) {
                song element = itr.next();
                if(element.getSource() == 0){
                    itr.remove();
                }
            }
        }

    //Second class

public class Tracks extends Fragment {


    RecyclerView list;
    private MediaPlayer mp = new MediaPlayer();
    SongListAdapter listAdapter;
    private ArrayList<song> songs = new ArrayList<>();
    ImageButton playButton;
    boolean playerActive = false;
    MainActivity mainActivity;
    int mLastFirstVisibleItem = 0;


    public Tracks() {
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        mainActivity = (MainActivity)getActivity();
        songs = mainActivity.songs;
        listAdapter = new SongListAdapter(getContext(),songs, mainActivity);
        listAdapter.notifyDataSetChanged();
        list.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        list.setLayoutManager(llm);
        list.setAdapter(listAdapter);
    }
}

In both classes I am getting a list of songs from MainActivity. 在这两个课程中,我都从MainActivity获得了歌曲列表。 In the Tracks class I am just filling the RecyclerView with it, and in the VKtracks I am deliting unnecessary items with iterator and filling another RecyclerView. 在Tracks类中,我只是用它填充RecyclerView,而在VKtracks中,我是用迭代器定义不必要的项目并填充另一个RecyclerView。 At the end i have 2 similar filtred lists. 最后,我有2个相似的过滤列表。 If I comment filtering part in the VKTracks class I am getting 2 similar unfiltred lists. 如果我在VKTracks类中评论过滤部分,则会得到2个类似的未过滤列表。

So, why this happens? 那么,为什么会这样呢?

The only reasong I can suppose is that both songs ArrayLists are poiners to a songs ArrayList in the MainActivity. 我可以推测的唯一原因是,这两个歌曲ArrayList都是MainActivity中歌曲ArrayList的指针。

Your reasoning is correct. 您的推论是正确的。 The pointers Tracks.songs , VKTracks.songs , and MainActivity.songs are all point to the same list, so modifying either will change all three. 指针Tracks.songsVKTracks.songsMainActivity.songs都指向同一列表,因此修改其中任何一个都将更改全部三个。 Try using the ArrayList copy constructor in Tracks and VXTracks to create three unique array lists. 尝试在TracksVXTracks使用ArrayList复制构造函数创建三个唯一的数组列表。 To do this, replace the line 为此,请替换行

songs = mainActivity.songs;

with

songs = new ArrayList(mainActivity.songs);

in both Tracks and VKTracks . TracksVKTracks

It looks like you have two subclasses of Fragment and use its "getActivity()" method with after initialising with "savedInstance". 看起来您有Fragment的两个子类,并在使用“ savedInstance”进行初始化之后使用其“ getActivity()”方法。

My guess is that in both cases the "songs" attribute gives you excatly the same pointer. 我的猜测是,在两种情况下,“歌曲”属性都可以为您提供完全相同的指针。 So if you modify the list in one place, this modifies it everywhere. 因此,如果您在一个地方修改列表,那么到处都会对其进行修改。

To stop this behavior try to copy this list before modifying. 若要停止此行为,请尝试在修改之前复制此列表。

You are right, fragment.songs = mainActivity.songs points fragment.songs to the list maintained in mainActivity. 没错, fragment.songs = mainActivity.songs指向fragment.songs = mainActivity.songs中维护的列表。

Thus, fragment.songs.remove(song) removes the song from that list. 因此,fragment.songs.remove(song)将歌曲从该列表中删除。

Also, altering a song in fragment.songs (eg adding a comment) would in fact alter that object in the mainActivity.songs list. 另外,更改fragment.songs中的歌曲(例如添加评论)实际上会更改mainActivity.songs列表中的该对象。

To avoid this behaviour, you'd have to create a copy of the list and its items. 为了避免这种情况,你必须创建列表项目的副本。

I am not exactly sure what you are asking, but I will try my best to give you a brief explanation of objects vs primitive values. 我不确定您要问什么,但我会尽力为您简要介绍对象与原始值。

Consider this code: 考虑以下代码:

int x;
int y = 1;
x = y; //x is now 1
y = 2; //y is now 2, but x is still 1
System.out.print(y); //prints 2
System.out.print(x); //prints 1

Since int is a primitive value and not an object, writing x = y; 由于int是原始值而不是对象,因此写x = y; does not make x point to y since y is not an object, there is nothing to point to. 不会使x指向y因为y不是对象,所以没有要指向的东西。 x just gets the value of 2 . x仅获得2的值。 This is the same as writing x = 2; 这与编写x = 2;相同x = 2; .

Now consider this code: 现在考虑以下代码:

Person x;
Person y = new Person("Johnny");
x = y; //x is now pointing to the same object as y
y.changeName("Felicity"); //this changes the name of the object to Felicity
y.printName(); //prints Felicity
x.printName(); //also prints Felicity

Since a Person is an object, writing x = y; 因为一个Person是一个对象,所以写x = y; does make these two variables point to the same object. 确实使这两个变量指向同一对象。 Any change made to the object via any variable is visible via the other variable as well. 通过任何变量对对象所做的任何更改也可以通过其他变量看到。

In short, 简而言之,

For primitive variable (eg int, double, char, boolean etc): No 对于原始变量(例如,int,double,char,boolean等):否

when you use x=y, 当您使用x = y时,

x then hold the value of y, change in y later on will not affect the value in x x然后保留y的值,以后更改y不会影响x中的值

For object (even Integer, Double): Yes 对于对象(偶数,双精度):是

since 以来

A x;
A y = new A();// here y holds the reference of a new object of class A created.
x = y // x then holds the reference of the same object of y

so x and y 'point to' the same object (They are called reference in Java's term) 所以x和y“指向”同一对象(在Java术语中称为“引用”)

Side notes: 旁注:

When you say 'point to', if you are talking about c++ pointers, then the answer is Yes for both primitive and object, but well, it is a Java question. 当您说“指向”时,如果您谈论的是c ++指针,那么对于原语和对象,答案都是“是”,但这是一个Java问题。

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

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