如何修改字段的字段...的公共领域作为link.next.next.next(。接下来* n)的n倍 [英] How to modify a public field of a field of a field… As in link.next.next.next(.next*n) n times

查看:154
本文介绍了如何修改字段的字段...的公共领域作为link.next.next.next(。接下来* n)的n倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个持有环节的数组。每个环节都有所谓的下一个公共领域,可容纳另一个链接,能容纳更多的链接等。当我要删除我的事情可以做。

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;

这将删除第二项。但我希望能够删除任何项目,所以我怎么能得到它与变量的形式?该公式将这些方针的东西:如果我想删除项n,我会做

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);

这意味着,如果N = 4我想exand到

Which if n = 4 I want to exand to

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

希望我的问题是清楚的。我需要知道如何做这种方式,因为我不能设置一个getter或任何其他code到我的链接类,因为即时通讯我的code的唯一拥有者,我不打算incorectly设置我的领域。 Java的。

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.

推荐答案

正如在其他的答案中提到,你什么实现是一个链表,你可能会提供最好的服务,以充分利用Java的类库。

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.

要解决这个问题,你提出的它,让你到第n跳的引用的功能可能是你问什么

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
}

这篇关于如何修改字段的字段...的公共领域作为link.next.next.next(。接下来* n)的n倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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