How to modify a public field of a field of a field… As in link.next.next.next(.next*n) n times

我只是一个虾纸丫 提交于 2019-12-20 05:53:07

问题


I have an array which holds links. Each link has a public field called next which can hold another link, which can hold any more links ect. When I want to delete things I can do

array[x].next = array[x].next.next;

which would delete the 2nd item. But I want to be able to delete any item, so how can I get it into a form with variables? The equation would be something along these lines: If I wanna delete item n I would do

array[x](.next*(n-1)) = array[x](.next*n);

Which if n = 4 I want to exand to

array[x].next.next.next = array[x].next.next.next.next;

Hopefully my question is clear. I need to know how to do it this way as I cannot set a getter or any other code into my link class, and since Im the sole owner of my code I am not going to incorectly set my the field. Java.


回答1:


As mentioned in other answers, what you're implementing is a linked list and you'd probably be best served to leverage Java's libraries.

To address the question as you posed it, a function that gives you a reference to the nth hop is probably what you're asking for

Link getLink(Link link, int hops){
  Link retVal = link;
  for (int i = 0; i < hops; i++){
    if (link == null){
       //hops is too large. Do something to indicate error
    }
    else{
       retVal = retVal.next;
    }
  }
  return retVal;
}

Then you could execute

getLink(array[x],2).next = getLink(array[x],4);

Or if you wanted to use reflection (not recommended since reflection is relatively expensive), then you could do something like

Link myLink = array[x];
Field next = Link.class.getField("next");
//assume proper error handling
for (int i = 0; i < hops; i++){
  myLink = (Link) next.getObject(myLink);
  //assume proper error handling
}



回答2:


Seems like what you have there is an array of linked lists. I don't know why you're worrying about this fancy syntax expansion stuff when what would work just fine is a method that deletes the nth node, and there are tons of implementations floating around the internet.

In fact, you can look at the source for java.util.LinkedList and copy that implementation yourself, with simple modifications if you have a singly linked list. Basic formula is:

  1. Iterate from the first node, repeatedly finding the next node until the nth node is reached
  2. Unlink that node from the chain



回答3:


Use a simple loop to step along n times. Here's some code that deletes the nth:

Link link = array[x], prev = link;
int n = ?;

for (int i = 0; i < n; i++) {
    prev = link;
    link = link.next;
}
prev.link = link.next;


来源:https://stackoverflow.com/questions/23718058/how-to-modify-a-public-field-of-a-field-of-a-field-as-in-link-next-next-next-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!