小编Ste*_*n B的帖子

Java 8流"ifPresent"

我试图了解流并遇到问题:我想获得列表的最小值并将其分配给int变量.为此,我做了以下事情:

List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    int smallest = list.stream().min(Integer::compareTo).get();
    System.out.println(smallest);
Run Code Online (Sandbox Code Playgroud)

这很好,我得到1了结果.问题是IDE会Optional.get在检查之前发出警告.isPresent.为了解决这个问题,我使用了略有不同的ifPresent方法并尝试了以下方法

int smallest = list.stream().min(Integer::compareTo).ifPresent(integer -> integer);
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于我收到警告,这不起作用:Bad return type in Lambda, Integer cannot be converted to void. 我的问题最终是:如何将min值分配给int smallest变量WITH检查ifPresent?

java lambda java-8 java-stream

11
推荐指数
2
解决办法
2万
查看次数

C#列出IList或IEnumerable作为参数

如果我想将List作为方法的参数,Resharper会提示使用IList接口可能是一个更好的主意.如果我然后用IList替换List,Resharper建议使用IEnumerable.在Java中,我还将List接口而不是ArrayList作为参数.但是使用iEnumerable作为参数是否真的很好看?如果不需要IList或List的功能,这是使用IEnumerable的好习惯吗?

c# methods ienumerable arguments list

4
推荐指数
1
解决办法
2439
查看次数

Java只需一步就可以将两个对象传递给对方

我有以下主类和主要方法:

public class Main {

Peter peter = new Peter(this);
Tom tom = new Tom(this);

    public static void main(String[] args) {
        Main main = new Main();
        System.out.println(main.peter.tom);
        System.out.println(main.tom.peter);
    }
}
Run Code Online (Sandbox Code Playgroud)

以及以下Parent类:

class Enemy {
     //some variables
}
Run Code Online (Sandbox Code Playgroud)

以及两个子课程:

class Tom extends Enemy {

    Enemy peter;

    Tom(Main main) {
        this.peter = main.peter;
    }
}

class Peter extends Enemy {

    Enemy tom;

    Peter(Main main) {
        this.tom = main.tom;
    }
}
Run Code Online (Sandbox Code Playgroud)

当两个打印方法在main方法中运行时,第一个返回null,因为Tom在分配时没有创建Enemy tom.为了解决这个问题,我没有在构造函数中分配TomPeter使用Enemy,而是在创建两个对象之后使用方法.所以更像这样:

private void …
Run Code Online (Sandbox Code Playgroud)

java class creation object

1
推荐指数
1
解决办法
509
查看次数

Python assert isinstance() 向量

我正在尝试在 python 中实现一个 Vector3 类。如果我用 c++ 或 c# 编写 Vector3 类,我会将 X、Y 和 Z 成员存储为浮点数,但在 python 中我读到ducktyping 是要走的路。所以根据我的 c++/c# 知识,我写了这样的东西:

class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \
               (isinstance(z, float) or isinstance(z, int))
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
Run Code Online (Sandbox Code Playgroud)

问题是关于断言语句:在这种情况下你会使用它们还是不使用它们(数学的 Vector3 实现)。我也用它来做类似的操作

def __add__(self, other):
    assert isinstance(other, Vector3)
    return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
Run Code Online (Sandbox Code Playgroud)

你会在这些情况下使用断言吗?根据这个网站:https : //wiki.python.org/moin/UsingAssertionsEffectively它不应该被过度使用,但对于我这个一直使用静态类型的人来说,不检查相同的数据类型是非常奇怪的。

python assert duck-typing isinstance

0
推荐指数
1
解决办法
2万
查看次数