小编Ole*_*hov的帖子

Java中"this"或私有对象的同步?

可能重复:
避免在Java中同步(this)?

这两段代码有什么区别?每个的优点和缺点是什么?

1)

public class Example {
    private int value = 0;

    public int getNextValue() {
        synchronized (this) {
            return value++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2)

public class Example {
    private final Object lock = new Object();
    private int value = 0;

    public int getNextValue() {
        synchronized (lock) {
            return value++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronization

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

Java中比较器接口的构造函数

我知道一个接口不能有构造函数,我们不能创建接口对象.

这是不可能的:

Comparator cmp = new Comparator(); 
Run Code Online (Sandbox Code Playgroud)

我不明白如何使用关键字"new Comparator()"创建一个匿名内部类.此关键字是否不会创建Comparator类型的对象?

这是完整的代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class DemoApp {

    public static void main(String args[]) {

        List<String> animals = new ArrayList<>();
        animals.add("elephant");
        animals.add("snake");
        animals.add("lion");
        animals.add("mangoose");
        animals.add("cat");
        animals.add("tiger");

        Collections.sort(animals, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return -s1.compareTo(s2);
            }
        });
        displayList(animals);
    }

    public static void displayList(List<String> anim) {
        for (String animal : anim) {
            System.out.print(animal + " "); 
        }
        System.out.println();
    }
 }
Run Code Online (Sandbox Code Playgroud)

java collections constructor interface

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

String str = new String("my string")效率真的低吗?

我经常看到人们说String str = new String("my string")写作效率低于写作,String str = "my string",因为前者创建了一个静态的"my string"对象,然后new是一个从静态复制的String对象.

但是,鉴于这里的语言非常简单明了,我很难想象Java优化器不会花费任何精力简单地将前者转换为后者.为什么它会选择以更费力的方式做到这一点?如果Java优化它会有什么负面影响?

java string optimization

6
推荐指数
2
解决办法
246
查看次数

如何使用java8中的Method参数打印多个参数


我正试图hashmap用两个java 打印出基本的.

Map<Integer, String> mp = new HashMap<Integer, String>();
mp.put(10, "apple");
mp.put(20, "orange");
mp.put(30, "banana");
Run Code Online (Sandbox Code Playgroud)

但是当谈到method referencejava8 时,我无法弄清楚如何打印多个参数.


我试过这样的事.但它给了我编译错误.

mp.forEach(System.out::println(i+" "+s););
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.
谢谢.

java lambda hashmap java-8 method-reference

6
推荐指数
3
解决办法
913
查看次数

删除yii2中的相关记录 - 最佳实践

我的数据库使用MyISAM引擎,因此我无法调用级联删除操作,因为MyISAM不支持它.同时,我想在我的yii2应用程序中删除相关记录.我怎样才能做到这一点?

mysql database activerecord yii2 yii2-advanced-app

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

无法将Yii2对象数据作为Json返回

我是Yii2框架和PHP的新手.当我尝试从服务器检索模型数据时json,我得到一个空的结果.但是,当我使用时var_dump,我得到一个非空的结果.

控制器类代码:

public function actionIndex() {          
    $client = new Client();
    $client->name = "ajith";
    echo json_encode($client);
}
Run Code Online (Sandbox Code Playgroud)

模型类代码:

class Client extends \yii\mongodb\ActiveRecord {
    public static function collectionName() {
        return ['gym', 'client'];
    }

    public function attributes() {
        return ['_id', 'name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'];
    }

    public function rules() {
        return [
            [['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
        ];
    }

    public function attributeLabels() {
        return [
            '_id'  => 'ID',
            'name' => 'Name',
            'age'  => 'Age', …
Run Code Online (Sandbox Code Playgroud)

php json mongodb yii2

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

子类构造函数中的 super 有何作用?

我目前面临关键字的理解问题super。我知道这super是对特定子类的下一个超类的引用。无论如何,我想告诉你我的问题:

public class Father{
    int length; 

    Father(String s){
        length = s.length(); 
    } 
}

public class Sub extends Father {
    char c; 

    Sub(String s) {
        super(s);
        c = s.charAt(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

super(s)该行在子类中做什么?如果我将 Father 类从公共类更改为抽象类会发生什么?

java abstract-class subclass super superclass

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

流 - 嵌套集合 - 转换为地图

假设我有2节课.

课程班

public class Course {
    private int id;
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

学生班

public class Student {
    private int id;
    private String name;
    private List<Course> courses;
}
Run Code Online (Sandbox Code Playgroud)

我有List<Student>,每个人Student都注册了多门课程.

我需要使用Java 8流API过滤掉结果,如下所示.

Map<courseId, List<Student>> 
Run Code Online (Sandbox Code Playgroud)

我在下面试过,但没有成功:

第一种方法

Map<Integer, List<Student>> courseStudentMap = studentList.stream()
    .collect(Collectors.groupingBy(
        student -> student.getCourses().stream()
            .collect(Collectors.groupingBy(Course::getId))));
Run Code Online (Sandbox Code Playgroud)

第二种方法

Map<Integer, List<Student>> courseStudentMap = studentList.stream()
    .filter(student -> student.getCourses().stream()
        .collect(Collectors.groupingBy(
            Course::getId, Collectors.mapping(Student::student, Collectors.toList()))));
Run Code Online (Sandbox Code Playgroud)

nested-loops java-8 java-stream

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

在这种特定情况下如何使用Streams获取列表列表?

我有一些类如下:

Class A {
    private String name;
    private List<B> b;
    // getters and setters
}
Class B {
    private String name;
    private List<C> c;
    // getters and setters
}
Class C {
    private String name;
    private List<D> d;
    // getters and setters
}
Class D {
    // properties
    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个类型列表A.我想要做的是获得一个包含其他类型列表的列表,D如下所示:

List<List<D>>
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情flatMap:

listA.stream()
     .flatMap(s -> s.getB.stream())
     .flatMap(s -> s.getC.stream())
     .flatMap(s -> s.getD.stream())
     .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但是这会将类型的所有元素收集D到一个列表中:

List<D>
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

java grouping list java-8 java-stream

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

实时编译器如何优化Java并行流?

前段时间,人们提出了一个有趣的问题:

Can (a == 1 && a == 2 && a == 3) evaluate to true in Java?
Run Code Online (Sandbox Code Playgroud)

我决定证明可以使用Java 8 Stream API(准确地说是并行流).这是我的代码在非常罕见的情况下工作:

class Race {
    private static int a;

    public static void main(String[] args) {
        IntStream.range(0, 100_000).parallel().forEach(i -> {
            a = 1;
            a = 2;
            a = 3;
            testValue();
        });
    }

    private static void testValue() {
        if (a == 1 && a == 2 && a == 3) {
            System.out.println("Success");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想,也许是因为潜在的JIT编译器优化?因此,我尝试使用以下VM选项运行代码:

-Djava.compiler=NONE
Run Code Online (Sandbox Code Playgroud)

我禁用了JIT,成功案例数量大幅增加! …

java parallel-processing jit jvm java-stream

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